$entity_wrapper->save(true) vs. entity_save('node', $entity)? Say I've got the following block of code:

$language = language_default();
$values = array([...]);

$entity = entity_create('node', $values);
$entity_wrapper = entity_metadata_wrapper('node', $entity);

$container = entity_create('field_collection_item', array('field_name' => 'field_container'));
$container->setHostEntity('node', $entity, $language);
$container_wrapper->save();
$entity_wrapper->save(true);
entity_save('node', $entity);

The above block of code invokes three different save() methods. Is this strictly necessary? Does entity_save cascade to $container_wrapper->save() and $entity_wrapper->save() if I do not explicitly call these? Are all three necessary?

Things appear to work find if I skip $entity_wrapper->save(true)...but am I missing something?

You need just one save call. All of them invoke the same code, the controller's save method (or node_save in node's case).

The wrapper modifies the original entity by reference, so it doesn't need an explicit save of its own (and the other way around).


Potentially cancel all other submit handlers after my own I've unshifted my own submit handler to the #submit handler of a node form. I already have a validation handler, so I can't execute my cancelling submit handler there.

Maybe this makes more sense:

my validation
all other validation
my submit handler, which potentially kills the submit process to form_state[rebuild] => TRUE and try again
all other submit handlers

Is that possible? I can cancel submission if I put my submit logic in a validation, but that's too soon. It should only run when all validation passes.

Ensure that your implementation of hook_form_alter() is the last one to be called. Your implementation of hook_form_alter() can then unshift one validation function and push a second validation function. The second validation function would then have complete information about whether other validation functions objected to saving the node (by calling form_get_errors()).

You can ensure that your your implementation of hook_form_alter() is the last one to be called by implementing hook_module_implements_alter()


When programmatically adding conditional element to webform, I get errors I'm trying to add a new conditional attribute to a bunch of webforms using a script.  There are already 12 conditions, and I need to add a 13th one.

My code looks like this in a basic script module which has $node available:

if(stuff_is_true){
 $new_component = array(
  'nid' => $node->nid,
  'rgid' => '13',
  'andor' => NULL,
  'action' => 'hide',
  'target_type' => 'component',
  'target' => '22',
  'weight' => '13',
  'rules' => array(
    '0' => array(
      'nid' => $node->nid,
      'rgid' => '13',
      'rid' => '0',
      'source_type' => 'component',
      'source' => '21',
      'operator' => 'equal',
      'value' => '0',
    ),
  ),
);

$node->webform['conditionals'][] = $new_component;

// Save the changes
node_save($node);

All of this works if put into a hook_node_view() (without doing a node_save obviously), so I know it's structured properly.

The problem comes during node_save($node) which throws an error like:

Duplicate entry '3033-0' for key 'PRIMARY': INSERT INTO {webform_conditional}...

(3033 is the nid, and the 0 is the rgid key).

Basically, what it's doing (I think) is trying to re-submit the whole $node->webform['conditionals'] array as NEW data, so existing components hit this "duplicate primary key" error (because they already exist).

How can I tell node_save to only ADD my new conditional item to the end of the existing array instead of trying to re-insert the whole thing?

It seems as if there's really no clean way to do this.  What I realized is that it was easier to just remove all existing conditions, and then re-add them all with the additional condition included.  So I started by setting:

$node->webform['conditionals'] = array(); //remove all conditions
node_save($node); //save the node, removing all old conditions
$node->webform['conditionals'] = $new_array_of_conditions; //add entire new array of condtions
node_save($node); //save the node with new conditions

This doesn't break anything on old nodes because no data or anything else is reliant upon conditions...so removing them doesn't hurt anything or lose any crucial data.


Change label max length on all field types The default max length for all labels of all field types is 128. The db can handle 255. So no schema change. How can I change the default max length to 250?

You can create a module and include the hook_form_alter for the content types you want. This is an example of how to do that:

function [MODULE_NAME]_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'your_form_id'){
    $form['your_field_name']['label']['#maxlength'] = 255;
  }
}

Also you can try this module: http://drupal.org/project/remove_field_label_length_limit


How to get the name of the current page view I'm trying to find a way to check the view name of the current page.

$views_page = views_get_page_view();
if (is_object($views_page)) {
    //get the view name
}

I haven't found any function that gives that information. Any suggestions?

views_get_page_view() returns a View object. The name should be stored in $views_page->name.


array_flip() error when using phpunit I've got a form, which when I use normally works perfectly fine, but when I load the form in phpunit I get the following error :

Drupal\digest\tests\DigestSubscriptionFormTest::testFormDisplay
Exception: Warning: array_flip(): Can only flip STRING and INTEGER values!
Drupal\Core\Entity\EntityStorageBase->loadMultiple()() (Line: 261)

Within buildForm I have something like this :
    $digest_storage = $this->entityTypeManager->getStorage('digest');
    $digests = $digest_storage->loadMultiple();
    $subscription_storage = $this->entityTypeManager->getStorage('subscription');

    /** @var \Drupal\digest\Entity\DigestInterface $digest */
    foreach ($digests as $digest) {

      $query = $subscription_storage->getQuery();
      // There should never be more than one ID returned.
      $subscription_id = $query->condition('digest', $digest->id())
        ->condition('uid', $this->currentUser->id())
        ->execute();

      /** @var \Drupal\digest\Entity\SubscriptionInterface $subscription_entity */
      $subscription_entity = $subscription_storage->load(current($subscription_id));
      $entity_exists = isset($subscription_entity);

Now when I am using this on my own it works just fine. No errors or warnings at all.
As soon as I get the page from phpunit I get the above error. Here's the test
  public function testFormDisplay() {

    $this->drupalLogin($this->adminUser);

    // Create some basic digests to view.
    $digest_storage = \Drupal::entityTypeManager()->getStorage('digest');
    $digest_storage->create([
      'id' => 'viewOne',
      'label' => 'View One',
      'enabled' => TRUE,
      'title' => 'Custom Title',
      'description' => 'Custom description',
      'send_at' => 'Monday',
    ])->save();
    $digest_storage->create([
      'id' => 'viewTwo',
      'label' => 'View Two',
      'enabled' => FALSE,
      'title' => 'Ghost',
      'description' => 'I\'m invisible',
      'send_at' => 'Friday',
    ])->save();

    // Load the subscription form.
    $this->drupalGet(Url::fromRoute('digest.digest_subscriptions'));

Adding the drupalGet line makes the test fail. If I remove the creation of the entities it works.
I'm not only wondering how to fix this but also why? This is a functional test so it should have a full site meaning I should be able to use the entityTypeManager as normal correct? Mocking is only needed for unit and some kernel tests right?

In the code shown for buildForm() there are two calls to loadMultiple():

The explicit call in the $digests = $digest_storage->loadMultiple(); line
The implicit call in the $subscription_entity = $subscription_storage->load(current($subscription_id)); line

The second line is an implicit call to loadMultiple() because the default implementation of load() (EntityStorageBase::load()) uses the following code.
assert(!is_null($id), sprintf('Cannot load the "%s" entity with NULL ID.', $this->entityTypeId));
$entities = $this->loadMultiple([$id]);
return isset($entities[$id]) ? $entities[$id] : NULL;

EntityStorageBase::loadMultiple() uses the following code.
$entities = [];
$preloaded_entities = [];

// Create a new variable which is either a prepared version of the $ids
// array for later comparison with the entity cache, or FALSE if no $ids
// were passed. The $ids array is reduced as items are loaded from cache,
// and we need to know if it is empty for this reason to avoid querying the
// database when all requested entities are loaded from cache.
$flipped_ids = $ids ? array_flip($ids) : FALSE; // This is line 261, in Drupal 9.0.x.

array_flip() raises the Can only flip STRING and INTEGER values! warning when the array passed as argument doesn't contain a string or an integer value, which also happens when the array contains one or more NULL values, or even FALSE values.
This means, for example, that the following line isn't setting $subscription_id to an integer or a string, possibly because there aren't any digest entity whose ID is $digest->id() associated with the subscription entity, or associated with the currently logged-in user.
$subscription_id = $query->condition('digest', $digest->id())
  ->condition('uid', $this->currentUser->id())
  ->execute();

This is the probable cause, giving that the code of that test isn't creating any subscription entity. If creating a digest entity is supposed to create a subscription entity, then it's not creating a subscription entity that is associated with a digest entity with that ID or with the currently logged-in user.
(I assume $digest->id() is returning an integer, since that is the usual case. I would verify that too, but since it's the test that is failing, it seems more probable the cause of the warning is the one I described.)


Database Connection error by giving specific IP address I have created database and user and give all the privileges to the user. When I give the IP as database host, it will show the following errors. Giving database host as localhost it will work fine.

I am using phpmyadmin 3.3.2...

The error message is given below.

  Failed to connect to your MySQL database server. MySQL reports the
  following message: Can't connect to MySQL server on '192.168.85.10'
  (111)

Definitely MySQL remote access would be blocked.

You can edit MySQL conf to enable it.
Loginto your remote db server and edit main configuration file.

vim /etc/my.cnf (in case of Linux)

Comment out skip-networking by adding # before it, should be located under [mysqld] and update bind-address for the desired IP you are using as connection host.

[mysqld]
...
...
bind-address = 192.168.85.10
#skip-networking


Deny access for Authenticated Users I'm using the moduke Permissions by Term and I love it. It works great and my complete system is now build around it. But I ran into a certain case and I am wondering if this is even possible.

I want a node to be visible for Anonymous users but not for a logged in user with a certain role.

Is it possible to do this. Is it possible to hide content or deny access for a certain role to content that is available for Anonymous users?

If you give a permission to the Authenticated User role, you grant that permission to all other logged-in roles. It works like this because all logged-in users get that role.

However, as long as you don't grant a permission specifically to the Authenticated User role, you can pick and choose which individual logged-in roles to give the permission to. Then you can also give the permission to the Anonymous User role.


Zen subtheme: no sidebar on a given page The overall layout of the site is composed of a 2 column layout (main content area + right sidebar). I have a /forum section on my site and I would like to have a single plain area for it and its childs.

Adding a forum.tpl page containing no sidebars does the trick?
Another way might be to prevent .sidebar-second being loaded as a
body class for a given URL (mysite.com/forum). Is this a clean way
to do it and above all will it escalade to /forum/subforums ?

I'm using a 7.x-5.x zen subtheme with D7 and Advanced Forum as the forum solution.

After some tests which involved using arguments in page.tpl and CSS trickery to clean up after, I couldn't manage to have a proper working solution.

Although I would have prefered to find a way to do this at a template level, easiest and quickest solution I finally found, was to use Context module

Basically I created a simple context with a Condition on path option and a Reaction on regions of the concerned theme. Checked the sidebar I wanted to exclude Saved and it was done.

Good thing doing this through the Context module is that, it removed the concerned regions, but most importantly it removed also the corresponding classes from <body> which were the pain in the butt to begin with.


Drupal Commerce Caching Modules I've been trying to improve the speed of my Commerce site with various caching and performance modules. But the general ones recommended don't work or break my site. I can't see anything else out there that answers my question!

Boost - I thought this would work on static pages such as About or Contact, but the module doesn't cache anything at all.

Agrcache - breaks the JavaScript slideshow on the front page.

Core Library - breaks the login page (which is odd!)

I have views cache installed and that's the only one I've got working so far...

You can use

https://drupal.org/project/commerce_entitycache

It will cache the commerce entities, rather than build them on each request.

While it works ok as is, after the two "Needs review" patches I added to the issue queue:

https://drupal.org/project/issues/commerce_entitycache?categories=All

I'm using it myself without any problems.

As mentioned previously:

https://drupal.org/project/authcache
https://drupal.org/project/commerce_authcache

Also work well with Commerce


Display Product Field twice I simply want to display Product Details twice on my page.

I use Display Suite for displaying all my fields on the node (Product Display) and for displaying the field twice, I would like to use a Dynamic Field. It lets me select the field but when I view my node I get a 500 Error.

Can someone help me please?
Thank you very much in advance for your help!

You can use Display Suite to duplicate your fields, go into Structure -> Display Suite -> Fields and add a dynamic field. Fill out the details specific to your node, etc.

On the Manage Display page of your content type you need to configure this field and select your product details, etc.


Is custom coding faster than Rules when reacting on user creation? I'm granting an avatar to the users on my website, based on their gender (cf. this answer). I've been able to achieve this both programatically and with 3 Rules.

This is my custom module:

function custom_user_presave (&$edit, $account) {
    $tid = $edit['field_geslacht']['und'][0]['target_id'];
    if ($account->is_new OR !isset ($account->roles[3])) {
        $avatar = taxonomy_term_load($tid);
        }
        else {
            $avatar = taxonomy_term_load(8);
        }
    $edit['field_avatar']['und'][0]['fid'] = $avatar->field_avatar['und'][0]['fid'];
    $edit['field_avatar']['und'][0]['width'] = $avatar->field_avatar['und'][0]['width'];
    $edit['field_avatar']['und'][0]['height'] = $avatar->field_avatar['und'][0]['height'];
    $edit['field_avatar']['und'][0]['alt'] = $avatar->field_avatar['und'][0]['alt'];
    $edit['field_avatar']['und'][0]['title'] = $avatar->field_avatar['und'][0]['title'];
}

This is one of my exported rules (the second only differs in the action part and the third one checks whether the user has a certain role):

{ "rules_avatar" : {
    "LABEL" : "Avatar",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "avatar" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_insert" : [], "user_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_geslacht" } },
      { "data_is" : { "data" : [ "account:field-geslacht" ], "value" : "Man" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-avatar:file" ], "value" : "35" } }
    ]
  }
}

I'm wondering which method is the fastest/most efficient. Can you help me?

I wouldn't focus too much on speed in situations like this because it's extensibility you will care about as the site grows in function. While your custom code is probably "faster" it's not the measure you should be deciding by since it'll be nanoseconds you're talking about and any good caching strategy will nullify most of that concern.

But to answer your question, your code would likely be faster especially if you're not defining as many hooks as the Rules module.

However, I'd advise using rules for the following reasons.

Rules are exportable
Rules are integrated with all the "big" modules out there.
Never program something you can borrow. :)

Hope this helps.


XML Source Won't import without a Source ID I'm using Drupal 8's Migrate API to pull in an RSS Feed as Nodes. The simple_xml data parser seems to require a Unique ID for the import or else I get an error on import.

The XML data is coming from the internet and only has one field applicable as a unique id, however it is preceded by a URL. I process the field with the substr plugin in order to pull in the ID, but when I run the import I get the following error message :

Migration failed with source plugin exception: field_guid has no value

The YAML file includes the following:

  source:
    plugin: migrate_gitem_xml
    data_fetcher_plugin: file
    data_parser_plugin: simple_xml
    urls:
      - www.somesite.com/source/xml-source.xml
  item_selector: '/rss/channel/item'
  ids:
    field_guid:
      type: integer
   fields:
    -
      name: title
      label: 'Title of the Item'
      selector: title
    -
      name: link
      label: 'Link to the Item'
      selector: link
    -
      name: body
      label: 'Body'
      selector: >
        content:encoded
    -
      name: guid
      label: 'ID of the Item'
      selector: guid
  process:
    type:
      plugin: default_value
      default_value: content_type
    uid:
    -
      plugin: default_value
      default_value: 1
    title: title
    field_link: link
    body/value: body
    body/format:
    plugin: default_value
    default_value: basic_html
    changed: '@created'
    field_guid:
    -
      plugin: substr
      source: guid
      start: 61
      length: 6

Any insight on how to get the Migration to work?

field_guid doesn't exist until the process pipeline runs, which is too late to use as a source ID. You can either simply use guid itself as your ID (with type: string), or do the truncation in prepareRow().


Discount for specific user group in Drupal Commerce I need to create 3 user groups and all of these groups must to have discount on all products in percent.

Example:

Group1 have discount of 10% on all products,
Group2 have discount of 13% on all products,
Group2 have discount of 16% on all products

Any idea how to do that?

Wait, wait, wait. That video tutorial referenced in the currently accepted answer is very outdated and unnecessary. All you need to do is create a new product pricing rule and use the "Multiply the unit price by some amount" line item action. Multiply it by .9 for a 10% discount, .87 for a 13%, and .84 for a 16% discount. Then just select the "Discount" price component (or else use a module to define a new price component type) in the action so it appears as expected in order total price breakdowns.

The only reason abusing the tax system was recommended at the time of that video recording was because you could not specify the price component type in the rules action. That has long since been changed, but alas the video still gets linked to quite a bit.


Hide fields on the user update form In dutch, postal codes are formed by four numbers and two letters, e.g., 1274EA. I want to split this info to a field that contains '1274' and another field that contains 'EA' in this case. Can I do this by creating two hidden user fields, or should I create a new entity type with a user reference field and the two fields? I prefer the first option, if possible. CSS is no option.

Have you tried the Postal Code module?

It seems to support dutch postal codes as well.


gmap macro doesn´t parse.. why? I have in my contact form something like

[gmap markers=big red::40.26041912699509,-3.8385844230651855 |zoom=15 |center=40.26217119406393,-3.840494155883789 |width=300px |height=200px |control=Small |type=Map]

but it doesn´t parse when I put it into the body of a content type

You need to create an input filter that uses the GMAP filter before it can work : Go to Administer > Site Configuration > Input format > Add Input Format and select the gmap filter in the filters list


Migrating Multisite Setup to Localhost Running Nginx 404 for /files I'm migrating a Drupal 7 based site to localhost. The site is currently setup in a multi-site configuration in the following way:

    webroot
    -drupal
    --sites
    ---example.com
    ----files
    ----settings.php
    ----sites.php
    ----modules
    ----themes
    ----libraries
    ----private

On my local dev server I imported the Db and set up the site in the following configuration:

 webroot
 -sites
 --example.com
 ---files
 ---settings.php
 ---sites.php
 ---modules
 ---themes
 ---libraries
 ---private

While I'm able to see the pages and login to the site, everything in my /files folder is returning a 404. All of the aggregated js files and images are broken and when I try to access any site admin links, I get an error.

I've check the permissions for the /files folder and files and everything seems fine. I've tried various suggestions like checking the .htaccess file, and adding $base_url in settings, and even turning off clean urls, but nothing seems to work. I even tried to set permissions on the folder and files to 777, but no luck.

Any suggestions or recommendations would be greatly appreciated.

I sorted this out. I'm using VVV Varying Vagrant Vagrants for my local development environment, https://github.com/Varying-Vagrant-Vagrants/VVV

Needed to customize the nginx configuration files for my site to accommodate a Drupal installation. The issue with the /files folder contents being 404 was largely due to this. After I configured nginx correctly for Drupal it worked like a charm.

You can find a sample config file here for Drupal: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/


How to properly restrict node access (including update/delete) based on field value? I have following requirements:

Users have (among others) role "tier1", "tier2" or "tier3". Higher value means more permissions and anonymous users are considered "tier0".
Users from tier2 and tier3 can create certain node type - MyNode. And only these users can update and delete them.
The node type MyNode contains (my custom) field for restricting access - it's a simple integer. 0 means all users can access it, 1 means users of tier 1-3 can access it, etc.

What's the proper way to implement the node restriction?

What I tried & longer description of the problem

After Googling and reading documentation, I found hook_entity_access. I simply iterated all fields and if I found my access field type, read the value and handle it. It was working pretty nicely for viewing, editing and deleting. But not for views - they completely ignored that.

After some more googling, I found that hook_entity_access/hook_node_access are ignored in views as explained on Node access rights. This page also explains that this problem should be solved by using  hook_query_TAG_alter, however I can't understand how it should be used. It seems to me I'm missing some bigger picture and failed to google it. But I found another solution - to use hook_node_access_records with hook_node_grants. I implemented this solution (with a tutorial help).

So each instance of MyNode provide grant based on field value, e.g. gid 2 means tier 2-3 can access the node. Each user is given grants based on their tier role, e.g. user with tier1 receive grants with gid 1, 2 and 3. This fixed view problem, but caused another one - if I set access of a node to 3, then users of tier 0-2 cannot view it (that's correct), but user of tier 2 can edit it (that's problem).

After some testing, it seems like permissions are handled differently for view and update/delete. View grant permissions are AND-ed with basic permission system (/admin/people/permissions), but update/delete permissions are OR-ed. I used the basic permission system to determine which roles can generally create, update and delete MyNode nodes.

So my current solution is merge of both approaches - grant system for views and hook_node_access for working with nodes directly. However, it seems to me quite hacky, dirty solution - I practically implemented same thing twice in different systems, because each system can handle only subset of all operations. And so, my question is - what's the proper implementation? What is correct Drupal-way?

Note: of course, I looked at modules to solve this. I rejected most of them, because they're still in alpha/beta/rc phase, while lifetime of D8 is ending. How much time I would have to wait for D9 implementation? Others were imho too bloated for "simple" "compare numeric value with role and accept/reject".

My system: Drupal version: 8.8.3

What's the proper way to implement the node restriction?

Don't re-invent the wheel ... The Group module is what you should be looking at.
It creates groups as entities, making them fully fieldable, extensible and exportable. For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types.

More info

Refer to "What are the various roles supported by the Group module?" for more details about the supported roles.
Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Complex delayed unpublishing I want a node that the user can edit the published setting on. (Via publish_content)

It should be unpublished by default 4 months after being published, but paused not reset when unpublished.

Also, there should be a cck field allowing the user to alter the time published beforehand but this should not be editable if the content has already been published and is in delay (Or unpublished and paused).

I've been looking at rules since this seems to be a pretty complex task, but I'm not exactly sure how to go about it and I'm new to rules.

After the initial (4 month) delay is over the user should be allowed to start this whole thing again.

Have a look at the rules scheduler module (part of the rules module). You should be able to do most of the things with date calculation and rules scheduler.

If you're missing something in rules you might have to implement your own rules action. Have a look at hook_rules_action_info().


Adding map with user location into the profile I am trying to add a 'IPGV&M: Map (Google) centered on visitor's location' block to all user profiles and I kinda succeeded. The map appears in the user profile, in the footer where i intended to have it, when I visit the user profile it asks if it can use my location. After clicking yes, I face couple problems:

It just shows a world's map from far far away without any marker on the location of a user
I have to make it so when visiting a user's profile I would be able to see where he/she is from in the map. If I use this method I talked about, doesn't it mean that when I visit someone else's profile I will be still seeing my own location? How to solve this problem?

I'm no expert but try using the Location Module.  It

  "..allows real-world geographic locations to be associated with Drupal
  nodes, including people, places, and other content"

God Bless.


Menu does not set active trail when generating tree in theme file I want to display the whole menu tree in my Drupal 8 theme to be able to show/hide submenus using javascript. To accomplish that, I added the following code to my theme file:

function pspartner_preprocess_page(&$variables) {

  $menu_tree = \Drupal::menuTree();
  $menu_name = 'main';

  // Build the typical default set of menu tree parameters.
  $parameters = new MenuTreeParameters();

  // Load the tree based on this set of parameters.
  $tree = $menu_tree->load($menu_name, $parameters);

  // Transform the tree using the manipulators you want.
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);

  // Finally, build a renderable array from the transformed tree.
  $menu = $menu_tree->build($tree);

  // Make menus available in templates
  $variables['main_menu_tree'] = $tree;
  $variables['main_menu'] = $menu;
}

This works, but the active trail is not set.

Set the active trail in the MenuTreeParameter object per MenuTreeParameters::setActivityTrail. This requires knowing the menu link plugin ids, which can be retrieved using MenuActiveTrail::GetActiveTrailIds (linked from the previous API page).

  $active_trail = \Drupal::service('menu.active_trail');

  // Build the typical default set of menu tree parameters.
  $parameters = new MenuTreeParameters();
  $parameters->setActiveTrail($active_trail->getActiveTrailIds($menu_name));


500 HTTP error on "Manage Display" tab after changing layout with Display Suite! What should I do? I changed the layout to "One column" with Display Suite on a given content type's "Manage display" tab, which has many (~30) fields. I'm also using Field group module with multiple groups.
After saving, DS has set some group's parent elements to "Disabled". OK, I changed it, I dragged these to the enabled part, and after saving, I got a 500 HTTP-code when going to "Manage display" tab after a long waiting time!

What should I do? Can I simply uninstall Display Suite module? Will it reset the display to my original settings and field orders?

Thank you for any kind of ideas!

EDIT

Uninstalling the module did NOT solve the problem.... I'm in a real big trouble, because I don't know how to reset the display...
Any ideas?

Had the same issue, deleting the rows corresponding to my problamtic content type from the table "field_group" solved it. This way I didn't lose my entire field group settings.


Why do I get "Theme hook ... not found" after renaming? I have a module to create and handle surveys. I made a theme originally for it called "survey" and everything worked fine. I am now trying to rename the theme/template to "questionList", but am getting "Theme hook questionList not found" in the logs.

My working code with the theme name "survey" is shown below.

survey.module

 /**
 * Implements hook_theme().
 */
function survey_theme($existing, $type, $theme, $path)
{
    $variables = array(
        'survey' => array(
            'variables' => array(
                'questions'    => NULL,
            ),
        ),
    );
    return $variables;
}

RadioQuestionController.php

    public function getAllQuestions()
    {
        $element['#questions'] = array(1,2,3,4,5);

        $element['#title'] = 'Radio Questions';
        $element['#theme'] = 'survey';
        return $element;
    }

survey.html.twig

{#
/**
 * @file
 * Default theme implementation to print list of questions.
 *
 * Available variables:
 *   - questions
 *
 * @ingroup themeable
 */
#}

Test

The above works fine and prints "Test" to the specified path in my .routing.yml file. However the following does not work.

survey.module

 /**
 * Implements hook_theme().
 */
function questionList_theme($existing, $type, $theme, $path)
{
    $variables = array(
        'questionList' => array(
            'variables' => array(
                'questions'    => NULL,
            ),
        ),
    );
    return $variables;
}

RadioQuestionController.php

    public function getAllQuestions()
    {
        $element['#questions'] = array(1,2,3,4,5);

        $element['#title'] = 'Radio Questions';
        $element['#theme'] = 'questionList';
        return $element;
    }

questionList.html.twig

{#
/**
 * @file
 * Default theme implementation to print list of questions.
 *
 * Available variables:
 *   - questions
 *
 * @ingroup themeable
 */
#}

Test

Is there something that I am missing that I need to change other than what is changed in the above code? Or is there something else going on?

function questionList_theme(...)

must have the name of the module, like :

function survey_theme($existing, $type, $theme, $path)
{
    $variables = array(
        'questionList' => array(
            'variables' => array(
                'questions'    => NULL,
            ),
        ),
    );
    return $variables;
}

will work.


How to programmatically edit a field? I have a type node called flat, a field called latitude. I want to update the value of this field in a module each time the node is updated.

I try to use the hook_node_update() but nothing happens :

function flat_node_update($node){
    print_r($node);
    return $node;
}

Do you have the answer?

hook_node_update() is called after the node has been updated.

You want hook_node_presave() instead. If the nid is not empty, it is an update.


How to make role field on approval in the Edit Profile page by Admin This website has over 1000 users with different profiles. Each user choose their profile on registration. On their Edit Profile page, the authenticated users can change or add more profiles to themselves. This was achieved by using the Role Delegation module and by changing some permissions.

Now, I would like to add another feature, namely, the role changing has to be approved by the administrator. This question is actually proposing what I'm looking for, but I cannot select the Role field, only the standard fields, such as First Name, or Last Name, or Email.
How can I achieve this additional feature?

Thanks!

UPDATE 1

I can try to narrow the question.  What I'm looking for is a rule, which notifies the Admin when a normal user changes its role, by sending an email. If possible, the rule should keep this edit unsaved until the Admin approves the change. Is it possible to achieve this kind of action?

You can't allow the users to change the role/profile directly, if this is what you want. What you'll need instead is another field to act as a proxy for the roles, so you would have a checkbox for each one.

Then you can use a rule to detect a change to the user and if there is a difference in the old and new values of this field, send an email to the admin.

I think this can probably all be done with contrib modules though it will not be a trivial matter, and would be easier to build and maintain with a little custom code acting as glue.


How to create a 3rd Ad push in a custom Omega Kickstart subtheme I'm using drupal commerce kickstart 7x to design an experimental website to understand the layout & methods of the CMS.

I've just started using Drupal. To be precise, 3 days. This is very new to me.

I want to know how does one go about placing a 3rd Ad Push block in the "Postscript third" section. I've sub themed Omega kickstart.

I've tried creating blocks, editing the fields, editing views, reordering the blocks and contents. Yet none seem to work.

I can only create a block with text as its body. But what I want to achieve is a 3rd block with an image in it just like the preceding 2 AD Push blocks.

How do I do it?

Images for reference:

Go to Site settings->Visual & Layout -> Views. You will see the View for Ad push blocks. Click on Edit for this View. Clone the Second ad push block. Be sure to:

change the name to Third ad push block
set the Pager to 1 item, skip 2
save changes

Go to Site settings->Visual & Layout -> Blocks and add the Third ad push block to the Postscript Third Region and click Save blocks.

Reload your page and the block should be visible on the front page.


load node author uid to be used as contextual link inside template.php D7 I need to load node author uid to be used as part of a href link inside template.php, I managed to add a contextual link according to this post, and call it from node.tpl.php but I can't access node author uid to complete my link. I have a view with the following path: /userview/%/post, link inside node.tpl.php it appears, but does not work. I tried to do it by custom module, but I do not know how to load the 'node being viewed' in a custom module, that's why I'm trying to do it in template.php. Any help will be appreciated.

This is my code in template.php

function MYTHEME_node_view_alter(&$build) {

         $node_author = user_load($node->uid);

          // Add your own custom link
          $build['links']['node']['#links']['user-post'] = array(
            'title' => t('User post'),
            'href' => '/userview/' . $node_author . '/post',
            'html' => TRUE,
            'attributes' => array(
              'title' => 'User post',
            ),
          );

        }

You have just a tiny mistake , use $build['#node']->uid instead $node->uid  :)

function MYTHEME_node_view_alter(&$build) {

         $node_author = user_load($build['#node']->uid);

          // Add your own custom link
          $build['links']['node']['#links']['user-post'] = array(
            'title' => t('User post'),
            'href' => '/userview/' . $node_author . '/post',
            'html' => TRUE,
            'attributes' => array(
              'title' => 'User post',
            ),
          );

        }


Change decimal separator to comma using commerce-order:commerce-order-total:amount_decimal I use D7 in a commerce website. I am setting up an email that will be sent to the user who just made an order.
In this mail, the token [commerce-order:commerce_order_total] is used to display subtotal, vat, shipping and total.

As you can see in the screenshot i use EURO as currency where the decimal separator is comma ','. (The translation is in Greek). So far so good.
After some information in the email, i need to indicate the exact amount that should be paid. I tried with token [commerce-order:commerce-order-total:amount_decimal] but as you can see the decimal separator is the dot and not the comma...

Is it something i can do to fix that ?

You can achieve it with hook_commerce_currency_info_alter(). Please do refer the discussion in this thread, you will get an idea.
Comma as decimal point


How can i create two register forms for different users? How can i have two register forms and show register form for two sets of users.

One register form for one set of users and another register form for another set of users?

one can be default drupal form that is user/register. But i want url to be varied.

Use the Profile2 Registration Path module. It can help you in creating as many registering forms as you need. I have used this one.

  This module enables administrators to set unique registration paths per Profile2 profile type.

  Overview

  The Problem

  By default, the Profile 2 module permits you to add fields from chosen profile types to the default user registration form. Unfortunately, there is only one user registration form. Thus, every user will be presented with these fields during registration. If you have two profile types targeted at two different audiences, you cannot have two separate registration forms.

Profile 2 use this module to get different set of fields. While editing the profile you have created, you can check this one.

Unique registration path
Enable unique registration path
Settings
URL path http://ram.site.dev/customer/register


Views with Entity Reference I'm not sure why this is difficult for me to get.  It seems like it should be simple.  I have a content type A and content type B.  Content type B has an entity reference field to content type A.  Content type B has an image field.

I want to display a view of type A, with all the images of a type B that reference it.

I've looked everywhere and it isn't making sense.  Can someone please point me in the right direction?

EDITED:  I figure it may help if I give a concept of what I'm trying to do. I have programs that I want to display.  For each program I have, one or more sponsors donate to the program.  When I display my view, I not only want to display my program content (content A), but also the logos of all the sponsors that donate to the program (content type B).  Right now, for each logo, I get a duplicate fields for my programs (content A).

In your case i would use the EVA Field module in combination with Display Suite module.

The EVA field module provides an extra views display plugin (EVA Field Display) that allows you to attach a view dynamically to a node, user, term etc.

The Display Suite module works great with EVA and helps you by letting place the attached view any where you want within the node display layout.

Create a content view and add an EVA Field display. In the Entity Content Settings of this display select:

Node for Entity type
Content type A for Bundles
Leave Arguments as it is (id)

Then:

Add a relationship for the entity reference field you have on content type B referring to A
Add the fields you want from content type B.
Add filter for content type = content type B
Add a contextual filter Content nid with the relationship of the entity reference!
Go to query settings and check the Distinct setting.

Now what will happen is that for every node of type A an EVA field view display will be attached showing the corresponding fields of node type B. Using Display Suite you can place this attached view any where you want in the node layout.

Hope this helps.


How do I use confirm_form()? I have a custom block made in the edit-mode of a node, and I would like to have it linked to a confirmation screen. So I figured out that I'll use confirm_form(). After a few days, I'm not able to get this function working.

Is there anyone who can tell me what I do wrong or what I'm supposed to do?

This is the switch statement that defines my actions when hitting the button.

case ACTION_FICHE_OFFLINE :
    if ($form_state['buttons']['5']['#value'] == ACTION_FICHE_ONLINE) {
      $form_state['values']['status'] = '1';
        drupal_set_message('FICHE ONLINE', 'warning', FALSE);
    }
    else {
      confirm_offline($form, 'Are you sure?', 'dashboard', t('This action cannot be undone'), 'Confirm', 'Cancel', 'fiche_offline');
      $form_state['values']['status'] = '0';
      drupal_set_message('FICHE OFFLINE', 'warning', FALSE);
}
    break;

The formal parameters for confirm_offline() are the following ones:

$form
$question
$path
$description = NULL
$yes
$no = NULL
$name = 'confirm'

What code should I use in confirm_offline()?

confirm_form() is a form builder; as such it should be called from a menu callback or another form builder function. From the code you shown, I take you are calling it from a form submission handler, and that is not how you should use that function.

As example of code that shows a confirmation form, you can look at system_modules(), the form builder associated with the "admin/modules" path. The function contains the following code.

  // If the modules form was submitted, then system_modules_submit() runs first
  // and if there are unfilled required modules, then $form_state['storage'] is
  // filled, triggering a rebuild. In this case we need to display a
  // confirmation form.
  if (!empty($form_state['storage'])) {
    return system_modules_confirm_form($visible_files, $form_state['storage']);
  }

The form submission handler for the "admin/modules" path, system_modules_submit(), then contains the following code.

  // Redirects to confirmation form if more modules need to be enabled.
  if ((!empty($more_required) || !empty($missing_modules)) && !isset($form_state['values']['confirm'])) {
    $form_state['storage'] = array(
      'more_required' => $more_required,
      'modules' => $modules,
      'missing_modules' => $missing_modules,
    );
    $form_state['rebuild'] = TRUE;
    return;
  }

Settings $form_state['rebuild'] to TRUE tells Drupal to call again the form builder which (basing on the value of $form_state['storage']) shows the confirmation form, rather than the form listing all the modules found for the Drupal site.


Search_api not searching taxonomy names I feel like I have tried messing with every setting I can find but I simple cannot make my search_api search view return any results based on taxonomy names.

I want to be able to search based on a custom taxonomy and search on the fulltext field of the name.

I am using the built in database.
I have added the taxonomy term database sources.
I have added a relationship for the taxonomy term on
my custom views
In the fulltext search on the view the taxonomy name field is selected to be searched
In the index I have added the custom taxonomy I want included.
I have set it to fulltext and boosted in to 5.0

What else am I suppose to do?

Does anyone know of any guide or any information that explains how to make this work? It has been a month I still cannot get this module to return content that has associated taxonomy terms.

Is there any modules that do this? It should be a standard use case...

I went through the same case, reinstall the search and entity modules. And try to install search_api using Database Search Default module and after installation, uninstall the database search Default module. Boost taxonomy name to 8 or 13. Then it should work.


How to Customize View Output I'm working on some views and I came across a requirement I'm not sure how to handle.

I need the title for each returned item to link to a specific URL. However, if another field (a link field) isn't empty, link to that link instead. I believe I need to edit the view template files but I'm not sure how to get started.

In my view, I've found the "Theme: Information" section and am able to get template files working for my view. However, it's listing display, style, row, and field templates. Where would I incorporate the logic I described above for the title field?
Once in a template file I am unsure of what variables are available to me. Is there a list or a way to discover these?

Views is rendered by some of *.tpl.php files, they are:

views-view.tpl.php. Main view template.
views-view-unformatted.tpl.php. Default simple view template to display a list of rows.
views-view-fields.tpl.php. Default simple view template to all the fields as a row.
views.view-field.tpl.php. This template is used to print a single field in a view.

If you want to use two different fields from one view in one file, I recommend to use views-view-fields.tpl.php where you can manipulate of all fields which you assign to view.

The views-view-fields.tpl.php has three variables to use: $view, $fields and $row. I suggest to use only $fields.

Then, if you have field named field_image you can render its using $fields['field_image']->content or $fields['field_image']->raw.

Also, I recommend to read more about it: Views template files


Add to cart button not displaying inside custom text in drupal 8 views I created a  product display view in drupal8 to display the product.
For this, I added some fields like product price, title, and " add to cart" form.
When I call all the fields inside custom text fields, the add to cart button is not displaying on the page.  To display the " add to cart" button, I am using

{{ variations_target_id }}

from replacement patterns.

AFAIK you can't rewrite the output of rendered entities (add to cart form) with replacement patterns for in D8 views.
I ran into this same problem and discussed it with the maintainer of the commerce_variation_cart_form module. You can read about it here: https://www.drupal.org/project/commerce_variation_cart_form/issues/3081903
Specifically this from comment #17 https://www.drupal.org/project/commerce_variation_cart_form/issues/3081903#comment-13269416

All the render code runs including the form generation and extra field addition, but anything in a views field rewrite is then run through Xss::filterAdmin() to remove dangerous tags, and apparently form is a dangerous tag


Why do I get these errors? I am getting a variety of errors when I try to use Drush and nothing seems to be working. I am able to run drush and see the help commands indicating that I have it installed; otherwise, I can't get anything to work. I get the following error when trying to update a module as an example:

  Command pm-update needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment to run this command.
  Command pm-update needs the following modules installed/enabled to run: update.
  The drush command 'pm-update insert' could not be executed.
  A Drupal installation directory could not be found

When I check the drush status output, I get the following, but it doesn't appear to have any of the other relevant site info that is shown in other examples (e.g. theme name, site name, etc.).

 PHP configuration     :  /etc/php.ini
 Drush version         :  4.5
 Drush configuration   :
 Drush alias files     :

Drush is currently installed in my home directory on a BlueHost shared account and my primary site is in the public_html directory; I have an additional site with a separate Drupal version and separate database in a subdirectory.

You need to call drush when you are within your Drupal folder. Otherwise drush does not know where your database is and so on.

cd /public_html/site2

Alternatively, you can set up a .drush/aliases.drushrc.php (Google should be able to tell you more about it) but that's probably not worth the effort in your case.


html5-respond.js not rendering CSS3 properties in IE7 and IE8 I am working on a drupal 7 website. I am using the zen theme as starter theme. But the html5-respond.js not functioning properly.

I have added border radius property for the boxes, but its not rendering in IE7,IE8. But the js is there and its calling properly.

Please advise me.

!DOCTYPE html>
<!--[if IEMobile 7]><html class="iem7"  lang="en" dir="ltr"><![endif]-->
<!--[if lte IE 6]><html class="lt-ie9 lt-ie8 lt-ie7"  lang="en" dir="ltr"><![endif]-->
<!--[if (IE 7)&(!IEMobile)]><html class="lt-ie9 lt-ie8"  lang="en" dir="ltr"><![endif]-->
<!--[if IE 8]><html class="lt-ie9"  lang="en" dir="ltr"><![endif]-->
<!--[if (gte IE 9)|(gt IEMobile 7)]><!--><html  lang="en" dir="ltr"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:dc="http://purl.org/dc/terms/"
  xmlns:foaf="http://xmlns.com/foaf/0.1/"
  xmlns:og="http://ogp.me/ns#"
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
  xmlns:sioc="http://rdfs.org/sioc/ns#"
  xmlns:sioct="http://rdfs.org/sioc/types#"
  xmlns:skos="http://www.w3.org/2004/02/skos/core#"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema#"><!--<![endif]-->

<head profile="http://www.w3.org/1999/xhtml/vocab">
  <meta charset="utf-8" />
<meta about="/files/clients/etihad/en/index" property="sioc:num_replies" content="0" datatype="xsd:integer" />

............

<!--[if lt IE 9]>
    <script src="html5-respond.js"></script>
    <![endif]-->

IE8 doesn't work on @import'ed stylesheets. but you can write query by this way

@ Media screen and (min-width: 980px)
{

  / * CSS Document * /

}

and also you must include css3-mediaqueries js

<! - Css3-mediaqueries.js for IE less than 9 ->
 <! - [If lt IE 9]>
 <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"> </ script>
 <! [Endif] ->

see this http://westilian.com/ie7-and-ie8-support-for-css3-media-query/


States visibility in type select and radio in drupal 7 I have a custom form

$form['basic']['legal_form'] = array(
  '#type' => 'select',
  '#options' => array(
    'option1' => 'option1',
    'option2' => 'option2',
    'option3' => 'option3',
  ),
  '#title' => 'My Dropdown',
);
//radio button to show if selected option3
$form['basic']['bearer_shares'] = array(
  '#type' => 'radios',
  '#title' => 'Radio Button to show',
  '#options' => array(1 => t('yes'), 2 => t('no')),
  '#states' => array(
    'visible' => array(
    ':input[name="legal_form"]' => array('value' => 'option3'),
    ),
  ),
);

I try too

':input[name="legal_form"]' => array('selected' => 'option3'),

If I change type to textfield it works as expected but not when I try to use radio. Can anyone suggest me what I am doing wrong.

Try this code

$form['basic']['legal_form'] = array(
  '#type' => 'select',
  '#options' => array(
    'option1' => 'option1',
    'option2' => 'option2',
    'option3' => 'option3',
  ),
  '#title' => 'My Dropdown',
  '#attributes' => array('id' => 'selection_id'),
);

//radio button to show if selected option3
$form['basic']['bearer_shares'] = array(
  '#type' => 'radios',
  '#title' => 'Radio Button to show',
  '#options' => array(1 => t('yes'), 2 => t('no')),
  '#states'           => array(
    'visible' => array(
      'select[id="selection_id"]' => array('value' => 'option3')
    )
  )
);


How do I properly add a custom source for RSS feed import? I am setting up the mappings for a Feed entity, but I cannot figure out how to properly set custom sources for fields.

In this case, I am grabbing records from an XML document ("RSS/Atom" option) and importing them into an Article content type.

I have a custom tag in the XML document, <alert>, with a value that maps to the Alert Flag Type (field_alert_flag_type) field on Article nodes. I set up a custom source called "Alert" (machine name alert), and when I attempt to import a feed with this new custom source specified, I get the following error(s):

The content [XYZ] failed to validate with the following errors:
    Alert Flag Type (field_alert_flag_type): This value should not be null.

Please check your mappings.

If the XML tag is <alert>, the source name is "Alert", and the source machine name is alert, what am I doing wrong?

The RSS/Atom parsers only work with predefined sources. The custom sources in this case are only useful when using them in combination with Feeds Tamper (or alike).

If you want more control about selecting data from a XML file, try the XML parser from Feeds extensible parsers instead. With that parser, you can select data from a XML file using XPath queries. So you are free to select about anything from a XML file.
It would be good idea to learn more about XPath before using the XML parser. I think that the XPath tutorial from W3Schools is a good resource for this.


How do I export and import content types (including fields) between environments? I've been trying to find a smart way of exporting content type and all its fields from one installation of Drupal to another.
The core "Configuration synchronization" export only export the content type, but not its fields and configuration.

So far I have not met anything applicable for Drupal 8. All I can find is mentions of this functionality is possible in Drupal 7 module called Bundle Copy, which was never ported properly for 8.

I've also tried this, however I cannot find any good documenation on how the "drupal config:import" or "drupal config:import:single" works.

Is it really so hard to export and import content types between environments or have I missed something essential?

You're on the right track with the configuration export but I am guessing you did the single export option for the content type. Each field on your content type has several configuration items that should be exported too.
An alternative is using the Features module. This will allow you to select your content type. It will also automatically gather up all the required configuration items for exporting them.


Access from different Network, one allow admin roles the other not I have a Drupal 7 site on a server wich can be accessed by 2 differents Network (A and B).
On both Network I use SAML to authentificate the users and affect them their roles (including back office roles) with SAML attributes.
When an user logs in from network A to my site he must have his back office options but when he logs in from network B he must not have them.

I want to block any administration feature, not just back office access so blocking urls will not be enough.
I don't want to see the edit/view tabs on content in the front office.
I don't want them to have access to content that is not published (even if they have access to it on network A).
Like the users had no back office role at all when they are on network B.

I am able to detect wich network the user is using on each visit and I have some code that allows me to affect the back office roles only if he comes from network A.

But if the user logs in first on network A then on his mobile access the site from network B and logs in he will lose his back office role on A unless he logout/login again.

Is there a way to disable all back office (admin) features on each visit if coming from network B? And not on each login? Aka a solution not involving removing his back office roles so he keep them when on network A.

Ok so the best solution I found wich might even work with a cache engine and without altering core was to remove the roles from the global $user in a hook_boot() :

function myModule_boot() {
  global $user;

  // if the user is connected and I am on network B
  if ($user->uid != 0 && variable_get('networkB', FALSE)) {
    // then we remove the role BO from the global $user
    // wich are stocked in a variable (roles_back_office) as a string (rid separated by pipes).
    foreach(explode('|', variable_get('roles_back_office')) as $rid) {
      if (isset($user->roles[$rid])) unset($user->roles[$rid]);
    }
  }
}


validation of text box and checkbox I am trying to validate the form. I have one hidden textbox and one check box group.

field_institute_event - represents checkbox group.
posted_student_list - represents hidden text box.

If both are empty then I want to display error message. How to do that??

I am trying following code:

if((empty($form_state['values']['field_institute_event']['und'][0]['entity']->field_institute_event_group[LANGUAGE_NONE]))
        &&
        (empty($form_state['values']['posted_student_list']['und'][0]['entity']->field_institute_event_group[LANGUAGE_NONE])) ) {
  form_set_error('field_institute_event_group',t('Please Post to atleast one group'));
}

if((empty($form_state['values']['field_institute_event']){
form_set_error('field_institute_event', t('YOURMESSAGE'));
}

That should do it. If you  want to validate on empty value on a required element.
You could also add the '#required' => true on your form element.


Dynamically add input field using #ajax As the question says, im not clear on how to go about adding new input fields depending on values of certain fields in the form.

I got as far as setting a callback and a wrapper, but i just can't seem to rebuild the form, i can do basic returns of values from the callback, but that's about it.

If anyone could show me a clean, simple way where i could go from, that would be great!

<?php

//Create raffle form
function raffle_create_form($form, &$form_state)
{

    //Basic raffle info
    $form['raf_raffle_name'] = array(
        '#type' => "textfield",
        "#prefix" => "
Raffle information

",
        "#title" => "Raffle Name:",
        "#required" => TRUE
    );

    $form['raf_allowed_number'] = array(
        '#type' => "textfield",
        "#title" => "Number of allowed members",
        "#required" => TRUE,
        '#element_validate' => array('element_validate_number')
    );

    $form['raf_start_now'] = array(
        "#type" => "checkbox",
        "#title" => "Start raffle now?"
    );

    $form['raf_end_date'] = array(
        "#type" => "date",
        "#title" => "When to close this raffle?",
        "#required" => TRUE
    );

    $form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#title" => "Prize type",
        "#ajax" => array(
            'callback' => 'raffle_create_form_type_steam',
            'wrapper' => 'steam_options',
        ),
    );

    if(isset($form_state['values']['raf_prize_type']))
    {
        $form['raf_steam_options'] = array(
            '#type' => 'textfield',
            '#title' => 'Added div',
            '#prefix' => '
',
            '#suffix' => '
'
        );
        $form['raf_steam_options']['#description'] = 'configure some steamy steam steam';
    }

    $form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        '#prefix' => '

',
    );

    $form['raf_prize_about'] = array(
        '#type' => "textarea",
        "#resizeable" => true,
        "#title" => "Prize description"
    );

    $form['raf_prize_thumb'] = array(
        '#type' => "file",
        "#title" => "Prize thumbnail"
    );

    $form['raf_prize_link'] = array(
        '#type' => 'textfield',
        '#title' => "Link to product"
    );

    $form['raf_raffle_create'] = array(
        '#type' => 'submit',
        '#value' => "Create Raffle",
    );

    $form['#submit'][] = 'raffle_create_form_submit';

    return $form;
}

function raffle_create_form_validate($form, &$form_state)
{

}

function raffle_create_form_submit($form, &$form_state)
{
    dsm('i printed');
}

function raffle_create_form_type_steam($form, &$form_state)
{
    dms('hi');
    return $form['raf_steam_options'];
}

You should do something like this

$form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#title" => "Prize type",
        "#ajax" => array(
            'callback' => 'raffle_create_form_type_steam',
            'wrapper' => 'steam_options',
            'event' => 'change',
           'method' => 'replace',
        ),
    );

$form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        '#prefix' => '
',
        '#suffix' => '
'
    );

And your callback function should be

function raffle_create_form_type_steam($form, $form_state){

    return $form['raf_prize_name'];
}


Bootstrap Theme $variables I've made a sub-theme of the Bootstrap theme; however, I am having trouble understanding where $variables comes from in the page.vars.php file. I made a little "debug" code to print out the variables - unfortunately, the output is exceptionally large and has some strange outputs. I have edited page.vars.php using the variables already retrieved from the $variables associative array, e.g. I edited the size of the main content section on the page:

 $variables['content_column_class'] = ' class="col-md-8 col-sm-6"';

This suggests there should be a 'content-column-class' in the $variables array; however, amazingly when I perform print_r($variables) it turns out there is none! Furthermore, every variable I have checked that is being accessed in page.vars.php seemingly does not exist.

I'd like to edit the class of the primary / sidebar_first sections; however, currently I cannot do this as I don't know how to access them from the $variables array.

In sum, why does print_r not output the expected? And, how do I find out what variables are actually in $variables?

The proper way to add a new variables in a class is to use hook_preprocess_page(&$vars) you can add the classes like the following:

$classes = array(
    'classes_main_page' => '',
    'classes_sidebar_first' => '',
    'classes_sidebar_second' => '',
  );

  // Classes when no sidebar
  if(empty($vars['page']['sidebar_first']) && empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-12 large-12';
  }
// Classes when left and right sidebars
  if(!empty($vars['page']['sidebar_first']) && !empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-6 large-6 columns';
    $classes['classes_sidebar_first'] = 'small-12 medium-3 large-3 columns';
    $classes['classes_sidebar_second'] = 'small-12 medium-3 large-3 columns';
  }

  // Classes when only left sidebar
  if(!empty($vars['page']['sidebar_first']) && empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-9 large-9 columns';
    $classes['classes_sidebar_first'] = 'small-12 medium-3 large-3 columns';
  }

  // Classes when only right sidebar
  if(empty($vars['page']['sidebar_first']) && !empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-9 large-9 columns';
    $classes['classes_sidebar_second'] = 'small-12 medium-3 large-3 columns';
  }
$vars = array_merge($vars, $classes);

and then in your page.tpl.php print something like this:

Don't forget to clear cache afterwards

<aside class="<?php print $classes_sidebar_second; ?>"> for sidebars
<aside class="<?php print $classes_sidebar_second; ?>"> for main container

Thanks


put the code into the template.php file? <div class="meta">
  <?php
    echo  $submitted;
    $common = $content['body']['#object']->field_fenlei['zh-hans'];
    foreach($common as $vocab){
      echo  l($vocab['taxonomy_term']->name,$vocab['taxonomy_term']->uri['path']);
    }
  ?>
</div>

This code is the one I wrote for node.tpl.php, and it's too bad. Is there a way to put the code into the template.php file? How do I do?

It's fine to put code in template.php, but do not print or echo there. All print or echo code should be in template files (.tpl.php). If you need to prepare variables for output in a template file, alter a preprocess function (eg. THEMENAME_preprocess_page if you need them in page.tpl.php), add your variables to the $variables array (eg. $variables['greeting'] = 'Hello!'; and print those variables in the template file (print $greeting;).

So for this example it would be something like:

function THEMENAME_preprocess_node(&$variables) {
  $common = $variables['content']['body']['#object']->field_fenlei['zh-hans'];
  $term_links = '';
  foreach($common as $vocab){
    $term_links .= l($vocab['taxonomy_term']->name,$vocab['taxonomy_term']->uri['path']);
  }
  $variables['fenlei_term_links'] = $term_links;
}

Now you can access the output with the variable $fenlei_term_links in your node.tpl.php:

<?php print $fenlei_term_links; ?>

In general you might want to use something like http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_links or http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_items


Cannot get subscriptions to send out at correct intervals I set up the "subscriptions" module and have set it so that all members of the page have access to a number of panels. One allows them to set the frequency of emails, one allows them to pick and choose which nodes to subscribe to.
The node choice works well, and so does choosing a 'digest' choice for the emails.

The issue I am having is that the notification emails are sent out at what seems to be the first cron event after the new content has been added, which can be a long time if I don't visit the site, but at the same time too soon if someone has chosen a longer interval.

I am currently the only one 'testing' the site so have two users set up with subscriptions. One I have set for once every 3 hours and one 'once per day'.

As Cron was only running when either entering the site or running manually, I also chose to download the module "Ultimate Cron" which I thought would run Cron more often (i have it set to 30 minutes), but it does not seem to be doing this either, although messages are being sent to both users, even if the one asking for a message no more than once per day has already received one in that 24 hour period.

If I don't visit the site, both now get messages at least, but not at the correct intervals.

One of the main organisers of our organisation says she will not join the forum and member site unless there is a way to get notifications once a day, or once a week, and she is trying to push to use Yahoo forums, but I have everything set up the way I like it and so if I can fix this one issue I can then open it up to members of our small society.

Here are some screenshots of my SUBSCRIPTIONS settings.
I have tried to show what I believe is relevant.
I have disabled the other subscription modules which I had tried in the past.
I DO have some messaging modules though (please see "messaging module" image)

UPDATE:
Tested again and still receiving messages on each cron run rather than at the correct intervals.
As mentioned below in a comment, it is likely an issue with the Subscriptions module.

If anyone knows how I may be able to fix settings, or even adjust line code to figure this out then I would be very grateful.

Had already tried notifications etc. but Subscriptions is perfect for what I need (if it worked).

Thank you all.

Setting cron to run every 3 hours does not necessarily mean that cron
  will actually run every 3 hours. This is because it is not truly
  automatic. Something needs to trigger cron to run. This trigger
  happens when a user visits the site. As part of dealing with the page
  request, Drupal will check for the last time that cron has been run
  and will run cron as part of the request if it is time to do so. If
  cron is set to run every three hours and three hours has passed since
  the last time it has run, it will run as part of the page request for
  the user that happens to hit the page at that time.

  But what happens if you have an extremely low traffic Drupal site,
  application or intranet? If no one visits the site at all, cron will
  not run. Or if a user visits the site and cron is run, and another
  user visits the site 2 hours and 59 minutes later, cron will not run
  because three hours hasn’t passed yet. If a third visitor visits 3
  hours later, then cron will run. But that is almost 6 hours since the
  previous cron run.

  Source: Why Drupal cron is not running as often as you think and how to fix it

The solution to this issue is to instead run/trigger cron from your server using crontab.

You can read about it here Why Drupal cron is not running as often as you think and how to fix it and goes over a solution using C-Panel.

If you don't have C-Panel you will have SSH into your server and manually add an entry to your servers crontab:

  The automated cron module has the disadvantage that it is triggered by
  a request, and the unlucky user who sends the request may experience a
  fairly long delay.  For this reason, the automated cron is typically
  used by smaller sites that are unable to create a cron job manually,
  e.g. using the Linux crontab.  If crontab is desired, Drupal console
  command may be used to simplify the configuration (rather than curling
  the long url show in /admin/config/system/cron.  Here is an example
  crontab entry:

30 * * * * web_user /var/www/html/vendor/bin/drupal --
root=/var/www/html/docroot cron:execute > /dev/null 2>&1

  This would execute Drupal cron once per hour at 30 minutes after the
  hour.

  Source: Automated Cron


Get submission values from a Webform I've got two fields in my form which are called geographicarea and specialty.

I'd like to use these values in an SQL query when the form is submitted.

How can I do it?

If I understand you correctly, you'd like to get a hold of the data before it gets inserted in the database so you can do something else with it?

If this is the case, hook_webform_submission_presave is your friend.
The $submission object will hold the submission data. This lets you change it before it's inserted in the database or, as in your case, just do something else with it.

Here's a list of all the webform hooks for D7 (with a link to D6 hooks as well if that's what you're using).


How to require one of two fields to be filled out? Let's say i have two fields in a content type. An integer field and a text field (two options with select list widget) and i want the user to fill out one of the two.
Can someone help me achieve this ?

Thanks

Have a look at the Conditional Fields module.


Drush Aliases into Remote Hosts not Working - Tried everything I've been struggling with a drush-related issue for awhile now and have more 'evidence' to write about. So here's what's going on: I'm trying to drush INTO two different servers (one on bluehost, another on rochen) and I get the same errors when I use my local drush on my computer to drush into either server. The error is Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

I get this error trying to drush @rochen status OR drush @bluehost status (the @name being the name of my alias files rochen.aliases.drushrc.php and bluehost.aliases.drushrc.php respectively.

I have installed drush on both servers already and can do drush commands on both using putty terminal.

I can drush just fine into Pantheon and any local sites I setup. I can also SSH into both rochen and bluehost just fine using Putty (I'm on Windows).

If I use drush --root=/home/username/public_html --uri=websiteurl status
it returns results...which is weird because I thought that command was supposed to be the same as doing drush @alias status which gives the error.

So I think maybe I have something wrong with my alias. See my alias file (I've confirmed the root is OK with my sysadmin):

<?php
$aliases['bluehost'] = array(
    'root' => '/home/username/public_html',
    'uri' => 'http://url.com',
    'remote-host' => 'url.com',
    'remote-user' => 'username',
);

// the following line is something I've tried to add in hopes it would help but it doesnt
//$options['ssh-options'] = '-o PasswordAuthentication=no -i C:/keys/ppkfile.ppk';

SOLUTION:

I fixed the permission denied error, the stdin: not a tty error, AND the bash: drush: command not found errors all in one fell swoop. See here: http://learningwithsage.com/wp/?p=236.

Try this first:

ssh-copy-id username@url.com

Make sure that the username and url match what is in your alias, of course.  The "Permission denied" error is complaining that the remote site does not have your public key stored in its "authorized keys" file.  ssh-copy-id will fix this for you.

If you are on a Mac, you can get ssh-copy-id from here:

https://github.com/beautifulcode/ssh-copy-id-for-OSX

It should be bundled with openssh on linux.


Is it possible to set: "show block on specific pages" into "is only the listed pages", programmatically? Is it possible to set: "show block on specific pages" into "is only the listed pages"?

I suppose that I should add a new item in this block info, but I don't know which one and can't find it in the api hook_block_info();
This block should be only visible in the page overview_courses/course but is visible in every page except overview_course/course

function menuNode_block_info() {
  $blocks['Course'] = array(
    'info' => t('Dit toont alle blocken weer'),
    'region' => 'sidebar_first',
    'weight' => 1,
    'status' => 1,
    'pages' => "overview_courses/course",
    'cache' => 'DRUPAL_NO_CACHE',
  );
  return $blocks;
}

Can someone help me? all help is welcome.

Kind regards

You need to set,  visibility => 'BLOCK_VISIBILITY_LISTED'

function menuNode_block_info() {
  $blocks['Course'] = array(
    'info' => t('Dit toont alle blocken weer'),
    'region' => 'sidebar_first',
    'weight' => 1,
    'status' => 1,
    'visibility' => 'BLOCK_VISIBILITY_LISTED',
    'pages' => "overview_courses/course",
    'cache' => 'DRUPAL_NO_CACHE',
  );
  return $blocks;
}


After insert data to table, updating data in home page drupal7 I have a insert_data module that used to insert data to category table, and I also have a module named mysite that has a function named “function mysite_preprocess_panels_pane(&$variables) “  is used to render data to panel.tbl.php.

My question is how can I call function “mysite_preprocess_panels_pane(&$variables)” from mysite module.

My purpose is after inserting data to table I want to show update data in home page(panel.tbl.php). I am new to drupal I need help or suggestion.
Thanks

Insert_data module

function insert_data($fn,$data) {
    $reply='';
    $status =1;
    $cid = db_insert('category') // Table name no longer needs {}
    ->fields(array(
   'name' => $data['name'],
   ))->execute();

   module_load_include('module', 'mysite', 'mysite');
   function mysite_preprocess_panels_pane();
   $reply= (array('status' => $status,'category' => $cid) );
   return $reply;
}

Calling mysite_preprocess_panels_pane() without parameter will be fine?

Mysite module

function mysite_preprocess_panels_pane(&$variables) {
    $query = db_select('category', 'n');
    $query->fields('n');
    $items = $query->execute()->fetchAll();

    $variables['ar'] = $items;
}

Panel.tbl.php

a
    <?php
        if (isset($variables['ar'])) {
             foreach (array_keys($variables['ar']) as $name) {
             print render($ar[$name]);
        }
     }

?>

Instead of implementing template_preprocess_panels_pane() and inserting your content there is something called ctools content types.

A ctools content type shows up in the panels interface as panes that can be added to a region.

In your case I would create a ctools content type in your module mysite.

Basically it's a block that contains rendered data that can be placed in a region of your choice.

It will be more easy to understand for other developers how the data is inserted on the front page also since it will be visible in the Panels interface.

/**
 * Implements of hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($module, $plugin){
  if ($module == 'ctools' || $module == 'panels'){
    return 'plugins/' . $plugin;
  }
}

Then create a folder in your module called plugins and in that folder create a folder called plugins. Place a file called MYPLUGIN.inc
The file should then be placed in mymodule/plugins/content_types/MYPLUGIN.inc

Place this content in your MYPLUGIN.inc

<?php

$plugin = array(
  'single' => TRUE,
  'title' => t('MYPLUGIN'),
  'render callback' => 'MYPLUGIN_content_type_render',
  'description' => t('Renders something.'),
  'category' => t('Custom'),
  'edit form' => 'MYPLUGIN_content_type_edit_form',
);

/**
 * Render the custom content type.
 */
function MYPLUGIN_content_type_render($subtype, $conf, $panel_args, $context) {
  $block = new stdClass();
  $block->content = 'MYDATA';
  return $block;
}

/**
 * Edit callback.
 */
function MYPLUGIN_content_type_edit_form($form, &$form_state) {
  $conf = $form_state['conf'];
  return $form;
}

/**
 * Implements hook_form_submit().
 */
function MYPLUGIN_content_type_edit_form_submit($form, &$form_state) {
  foreach (element_children($form) as $key) {
    if (!empty($form_state['values'][$key])) {
      $form_state['conf'][$key] = $form_state['values'][$key];
    }
  }
}

Now replace $block->content with the data you want to be rendered.


Dynamic css from node? I like to implement this codepen into drupal but the images in the background should come from a ctype within Drupal.

The codepen example:
http://codepen.io/AmeliaBR/pen/myPBNg

So basically how to get this line dynamic in a page?

article {
  background: url(https://foo.com/fooimage.jpg) no-repeat center;
}

Can you point me to the good direction? Is there a module which support this? What tags should I look?

You could use:

// replace this with the url from the node object
$imgURL = 'https://foo.com/fooimage.jpg';
$style  = 'article {';
$style .= 'background: url(' . $img_url . ') no-repeat center;';
$style .= '}';
drupal_add_css($style, array('type' => 'inline'));

For the $img_url though you need to fond out how to get the image url. You would need to load the node using node_load() then use dsm() from the Devel module or just use print_r() to display the field array.


How to filter on taxonomy term but only match one field on the node, where two fields (primary and secondary) both use the same vocabulary Using Drupal 7 Views > Contextual Filter, how can I filter on taxonomy term but only match one field on the node, where two fields (primary and secondary) both use the same vocabulary?  I have a vocabulary "Category" and I have organization nodes that can reference a category in either a Primary or Secondary field.  The concept is that organizations can primarily serve one topic of interest but can secondarily serve others.

I thought I had great, early success, but on closer inspection, the term is matching against both fields (like taxonomy ought).  I have had no luck in setting up only the primary field as the contextual filter for a term name, nor have I been able to first filter on taxonomy and then filter on the primary field.

What am I missing here?

Edit: Hmmm.. I wonder if it's because content fields in Views maybe match on "value" and category fields present themselves as "tid"?

Note: I don't think this is the same as Drupal 7 views contextual filters taxonomy name 2 fields using same vocabulary but I do love the way that one was titled!

Ok - This is also out of the box Taxonomy Term behavior.  My issue was I was selecting the wrong option for what I wanted.  I wanted the behavior that converts term string to tid, and so the full solution is:

Contextual filter on Content: Primary Category field
Specify Validation > Taxonomy Term, my vocabulary
Select the option Term name converted to Term ID

Bam!  Success!  Now I get my list of nodes matching that vocabulary's terms as strings but only for the one of the multiple taxonomy fields of that vocabulary on the node.  To further exemplify, my next step will be to create another View that is all the Secondary matching terms as "related" but not primary like this one is.


How can i attach my content type to level 1 taxonomies in multilevel taxonomy in drupal 7? I am using the default taxonomy of Drupal 7. I have a taxonomy like the following one:

Multilevel taxonomy (Vocabulary)

level 1 taxonomy  (Term)

level 2 taxonomy (Term)

I want my blog post have a field type of level 1 taxonomy.

Is there any module for this?

Checkout Hierarchical Select module. It offers many features.

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!


How do you call ubercart's shopping cart block? I have a need to manually call and place the UC shopping cart block. I know that to call the block it would be something like this;

<?php
$block = module_invoke('block', 'block_view', #);
print render($block);
?>

I tried;

<?php
$block = module_invoke('block', 'block_view', 'cart');
print render($block);
?>

and

<?php
$block = module_invoke('uc_cart', 'block_view', 'cart');
print render($block);
?>

Neither worked. How do I properly do this call?

I was able to render the code using the following;

<?php
  $block = block_load('uc_cart', 'cart');
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>


add custom markup on a specific element/filter in a exposed filter (views) I'm trying to learn how I can add or modify a markup for a specific filter on my exposed filter. I'm currently rendering the exposed filter using a block it has a lot of Drupal Generated Markup.

So far I've managed to identify the ID of the form, have been researching throughout the day for some examples but so far haven't had any progress

function iom_form_views_exposed_form_alter(&$form, $form_state, $form_id) {

    print_r($form_id);
}

Let say for example I have to add a label with a class and a custom class on the select element and wrap it with a div. Is there a way to build or construct that modified markup?

You can override the twig template responsible for that particular HTML output. You already see debug hints so you can see which template to check out.

Then copy that template to your subtheme and edit it there. Don't edit the core Drupal theme to avoid messing up your project maintainability.

Working With Twig Templates

You might be after select.html.twig and function template_preprocess_select.


How to make a block visible only to one page I have made a custom block and i want to make it visible only to pages that follow this pattern: user/[user-id]/galleries.

Is there a way to do it?

There are Visibility settings for blocks in Drupal. One of options is "Show block on specific pages". Select "Only the listed pages" and input user/*/galleries


How do i add custom jquerry script to omega theme? I found this code:

 (function ($) {
 Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
   attach:function (context, settings) {
     // first collapse the children
     $('ul.bef-tree-child').css('display', 'none');
     $('.form-checkboxes.bef-select-all-none li').has('ul').once('bef-tree', function () {
       $(this)
         .find('input.form-checkboxes:first')
         .click(function() {
           $ul = $(this).parents('li:first').find('ul');
           if($(this).attr('checked')) {
             $ul.slideDown('fast');
           }
           else {
             $ul.slideUp('fast');
           }
         })
     });
   }   } }) (jQuery);

for expandable hierarchy filters from here

I have no idea how to put it in my theme, what files and how to edit. Anyone could tell me the steps to do that?

There are (at least) two ways to add a JavaScript file to an Omega subtheme. The Omega Theme Documentation Handbook adds it as a library that can then be toggled on in the theme settings. I tend to use drupal_add_js, with a slight workaround to point it to the subtheme (more about why that's necessary in the Docs issue queue).

As a library

First, add the file to a js folder in your theme. The path to mine was sites/all/themes/webbykat/js/webbykat.js.

Second, add a reference to the new file in your theme's .info file. During this step, you'll also add some identifying information for your new file, like a name and a description, as well as its weight. Here's what mine looked like:

libraries[MYTHEME_custom][name] = Some custom name
libraries[MYTHEME_custom][description] = Some custom description
libraries[MYTHEME_custom][js][0][file] = script.js
libraries[MYTHEME_custom][js][0][options][weight] = 15

Be sure to clear your cache after you update your .info file.

Please note: If you're adding more than one file, you'll need to up that number for each file - libraries[MYTHEME_custom][js][0][file] = script.js and then libraries[MYTHEME_custom][js]3[file] = secondfile.js. Be sure to adjust it next to the weight as well. (Thanks, Screenack, for pointing that out in the
comments.)

Third, now that the Omega theme is aware of your new file, formally inform Omega that you'd like to use it. Under Appearance > Settings > [Theme name],  go to the Toggle libraries tab. Check the box next to the name of your file. Save.

With drupal_add_js

In template.php, you might think you could use drupal_add_js to add it like this:

function MYTHEME_preprocess_page(&$variables) {
  drupal_add_js(path_to_theme() . '/js/script.js');
}

However, path_to_theme doesn't reference the active theme (more on that here), so we need a slight workaround. Instead, use the following:

function MYTHEME_preprocess_html(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/js/script.js', array(
    'scope' => 'header',
    'weight' => '15'
  ));
}

Scope tells the function that the file should be called in the header or footer, and the weight tells it what order it should be called in relative to other files.

I prefer the two methods above because one is featured in the Omega documentation, and the other allows you to control what pages the JavaScript is called on if you want to (post on that to come). But as a developer friend pointed out, if you just want something quick and dirty to get a JavaScript file called on every page of your site, scripts[] = js/script.js in the .info file works too.

Source


Is that a way to sync Drupal databases I'm working on an existing website. So before I started I copied all files and database to my local environment. So far so good. To port the changes over I'd planned on using features. For a number of reasons the project got slightly off track I can't no longer migrate the features using the features module. Other than trying to fix why I can't port the features to the live site, I've been wondering whether is there a way to sync the two databases (effectively moving all the content - nodes, taxonomies and users - from the live site to the local site). I've tried Migrate Drupal to Drupal but the content wasn't imported. (I'm also looking at why it didn't work) but my question now is:

Are there any options to do it ? How ? (Other than Migrate Drupal to Drupal or using Features to migrate the features over)?

There are a couple of other options you can explore, apart from the ones you have already mentioned:

drupal sync
The present module allows synchronizing content among multiple websites.
Supported entity types: node and taxomony, menu items.

deploy
The Deploy module is designed to allow users to easily stage and preview content for a Drupal site. Deploy automatically manages dependencies between entities (like node references). It is designed to have a rich API which can be easily extended to be used in a variety of content staging situations.


drush migrate-manifest not found I'm trying to migrate a D7 site to D8 following this tut: http://www.metaltoad.com/blog/migrating-taxonomy-drupal-7-to-drupal-8

When I run

drush migrate-manifest manifest.yml --legacy-db-url=mysql://{dbuser}:{dbpass}@localhost/{dbname}

I get the error:

The drush command 'migrate-manifest' could not be found.

I'm using drush version 8.0-dev. Installed via composer. I also tried version 7.* and got the same message plus "Drush 7.0.0 does not support Drupal 8." What gives?

Now this has been moved to Migrate Manifest module. You can enable this module and use drush migrate-manifest command.


Show all nodes in the Getlocations map with diffrent marker colors per Content Type? I have three content types with Getlocations Fields and try to get a map with views (type: Getlocations) showing all nodes as marker in the map with different marker colors with "Content Type Markers" activated in admin/config/services/getlocations. I get only blue markers, this is the "Default Content Map marker". What is the trick?

Thanks for help.

There is a bug in getlocations.views.inc line 96 & 97:

if (isset($options['node_marker__' . $location['type'] . '__' . $location['field_name']])) {
              $marker = $options['node_marker__' . $location['type'] . '__' . $location['field_name']];

You need to strtolower $location['type'], then it works:

if (isset($options['node_marker__' . strtolower($location['type']) . '__' . $location['field_name']])) {
              $marker = $options['node_marker__' . strtolower($location['type']) . '__' . $location['field_name']];


How can users set their own price for their products? This question is a followup question to my prior question ...

Consider authenticated users of site are "STOREs". Any store (= user) should be able to set the product's price in their profile. So that product A sells at 200$ for Store B and sells at 150$ for Store C. How can I do it? I want Stores can set their price in their profile.

Assuming that you are using the Flag module (as I suggested in my answer to your prior question to "How authenticated users can choose favorite products and show them in their profile?", you could implement an extra (price) field when you define a flag. Such field can then be used to store the Product's price.

So if a user (= Store) then flags a product (to indicated "This store sells this product"), such user could use the extra field to actually indicate the price for that store.

Refer to the community documentation about Attaching fields to flags for more details about this.


Impossible to enable modules in SimpleTest I am building SimpleTests for my modules:

It seems like the standard procedure for enabling modules it doesn't work for me:

function setUp() {
    parent::setUp('mymodule');
 }

I constantly get a stupid error code: Duplicate entry 'bartik-system-main' for key 'tmd': INSERT INTO {block}

As I am using profiles I used the $profile variable:

protected $profile = 'myprofilename';

I have forced this by using a Drupal function:

module_enable(array('mymodule'), $enable_dependencies = TRUE);

In this final case the error that persists is

Undefined property: stdClass::$name

Here below is a sample of my code:

class mymoduleWebTestCase extends DrupalWebTestCase {

  protected $privileged_user;

  protected $profile = 'myprofile';

  public static function getInfo() {
    return array(
        'name' => 'mymodule',
        'description' => 'mydescription.',
        'group' => 'mygroup',
    );
  }

  function setUp() {
    $this->privileged_user = new stdClass();
    parent::setUp();
   // Login a user that has access to the content sync server admin settings
    $this->privileged_user = $this->drupalCreate();
    $this->drupalLogin($this->privileged_user);
  }

  function testMyModule() {

    //Create content of community type
    $settings = array(
      'type' => 'mycontenttype',
      'title' => 'Sample Content',
      'link' => 'http://www.google.com',
      'body' => array(LANGUAGE_NONE => array(array('body'))),
      'moderate' => 1,
      'status' => 1,
      'revisions' => NULL,
      'taxonomy' => NULL,
    );
    $node = $this->drupalCreateNode($settings);
    $this->drupalGet('mymodule/sample-content');
    $this->assertRaw('Sample Content', t('Content created.'));

    $node = $this->drupalCreateNode($settings);

   //This if we have a valid link inside
    $this->clickLink(t('http://www.google.com'));

  }

You should make triple-sure that your module declares all of its dependencies properly. Even if it does, Simpletest struggles with dependencies and you may have luck if you enable them explicitly in setUp() before your module.

Also, not sure if it's the contributing your error, but instead of $this->privileged_user = new stdClass(); I would use DrupalWebTestCase::drupalCreateUser like so: $this->privileged_user = $this->drupalCreateUser(). I might also declare it after setup() but I'm not sure that's significant.


Disable field validation of custom line items when cart is modified How to disable custom line item's field validation when line item is removed from cart?

My line item has a required field and if product/line item is removed from cart it still tries to validate it.
This causes form errors which isn't required.

You need to search for this function (since your not giving full information about that custom module you have)

function nameOfModule_form_validate(&$form_state, &$form_id){

You can search inside that function where it is doing the validation


Apache solr filter based on array values Has anyone succeeded in filtering array values using Apache solr? I have nids as an array, programmatically I want to use the array to filter the solr based on the 'entity_id'.

I tried something like

  $solr = apachesolr_get_solr();
  $query = apachesolr_drupal_query("custom", array('q' => ''),'sort_label asc', 'search/site');
  $query->addFilter('entity_id', '[10915 11013]');
  $response = $query->search();

But I don't get the desired results, somewhere the apachesolr_search or apachesolr module seems to be adding quotes to the filter values something like

webapp=/solr path=/select params={sort=sort_label+asc&start=0&q=&json.nl=map&wt=json&fq=entity_id:"[10915+11013]"&rows=10} status=500

I finally figured it out. Just a small change to what Clive suggested will solve the issue.

$query->addParam('fq', "entity_id:(10915 OR 11013)");

The above code gives me the expected response, i.e., result of node 10915 and 11013.

Hope this helps :)


A question about views and how to let sub menus link to the view like the main menu I created a view, like products. The path is /products, and the normal menu item is products
and I have a vocabulary with the name products.

The vocabulary's terms list:

product-a
product-b
product-c

I used the module "taxonomy menu" to link the taxonomy to the path /products

My question is:
when I browse /products, the page of products views will appear,

but when I click product-a, or product-b or product-c, they do not link to products views.

How can I get products views when I click on a sub menu item?

By default a link will be created to the full node view, as you described. When you want an item to link to another url, you need to rewrite the url.

To do so go to the view settings page and click on the field you want the link to be different of. Next go to the 'rewrite results' part of the settings schreen. check 'display field as link' and enter the correct url in the 'path' field.

Hope this helps