Ajax Forms created by Ajax Drupal 7 ERROR JAVASCRIPT I read a lot of documentation, specially this post https://www.drupal.org/node/2009252 but doesnt work for me.

This is my code, and the main problem is that i dont get the javascript in function hcat_my_account_create_companion_ajax_callback from the page callback 'my-account/ajax/create-companion' then I cant send my form by ajax.

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

    $items['my-account/ajax/create-companion'] = array(
        'page callback' => 'hcat_my_account_create_companion_ajax_callback',
        'access callback' => TRUE,
     );

    return $items;
}

function hcat_my_account_create_companion_ajax_callback($form, &$form_state) {

    $submission = (object) array();
    $form = render(drupal_get_form('hcat_my_account_acomp_form', null, $submission, true, false));

    $settings = FALSE;
    $javascript = drupal_add_js(NULL, NULL);
    if(isset($javascript['settings'], $javascript['settings']['data'])) {
        $settings = '';
    }

    form_load_include($form_state, 'inc', 'node', 'node.pages');
//I CANT PASS ANY JAVASCRIPT. WILL DISAPPEAR.
    return "
".$form.$settings."
";
}

function hcat_my_account_acomp_form($form, &$form_state, $vars) {

    $form['hola'] = array(
        '#type' => 'textfield',
        '#default_value' => "Vamos",
        '#attributes' => array('class' => array('my-account-input-edit')),
    );
    $form['submit_save'] = array(
          '#type' => 'submit',
          '#value' => 'Vamos que te quda poco',
          '#ajax' => array(
                'callback' => "hcat_my_account_create_attend_form_submit_ajax",
                'wrapper' => "hcat-my-account-acomp-form",
                'method' => 'replace',
                'effect' => 'fade',
              ),
    );

    form_load_include($form_state, 'inc', 'node', 'node.pages');

    return $form;
}

function hcat_my_account_create_attend_form_submit_ajax($form, &$form_state) {
    return "Desde la funcion hcat_my_account_create_attend_form_submit_ajax";
}

I found this way to resolve it. Creating another form whose submit return the form that i want. The code is:

function my_module_botton_create_form($form, &$form_state) {
    $form['create_form'] = array(
        '#type' => 'submit',
        '#value' => '',
        '#ajax' => array(
            'callback' => "my_module_to_create_form",
            'wrapper' => "new_acomp_form",
            'method' => 'replace',
            'effect' => 'fade',
          ),
    );

    return $form;
}

function my_module_to_create_form($form, &$form_state) {

    $form=drupal_get_form("my_module_acomp_form");

        $output = array(
            '#type' => 'ajax',
            '#commands' => array(
                array('command' => 'ajax_create_form_acomp', 'data' => drupal_render($form)),
            ),
        );

        return $output;
}

function my_module_acomp_form($form, &$form_state) {

    ...

    return $form;
}

The JS is

Drupal.ajax.prototype.commands.ajax_create_form_acomp = function (ajax, response, status) {
    $('#new_acomp_form').replaceWith(response.data+"

");
    //Drupal.behaviors.hcat_my_account.check_if_attendant_exits();
};


Field variable customization in node.tpl.php i have a website in which i am building a custom node page: node--coupon.tpl.php in which i want to render the body field only for which i used

  print render($content['body']);

The result is shown as "BODY: this is my text".

but i want to use only 'this is my text' which is entered at the time of making a new custom content type of coupon.

is it possible to do so anyhow?

If you want to hide the label, go to Admin > Structure > Content types > Coupon > Manage display.


When using the Real Name module, how can I show the original (raw) username in a view? The Real Name module allows a field in the user profile to be displayed as a user's name instead of the user name set upon registration.

This works great for my site as it allows people to set nicknames without having to worry about them being unique, etc.

However, I want to create a view for administrators that lists the actual (raw) username, not the real name.  When I add a User: Name field in views, though, the real name is displayed, and I don't see any option for the raw result.

How can I show the raw result in Views when Real Name is installed?

You're right in using the field User: Name as there is no explicit Raw name field (only a token). Now in the field settings you must uncheck Link this field to its user and More > Use formatted username.

If you still want to have a link to the user's profile, do some field rewriting: add User: uid, move it above User: Name, check Rewrite results > Output this field as a link with the path user/[uid] or user/[uid]/edit.


Suggestions for Adding Documentation to a Drupal Application I've built a pretty robust application using Drupal and currently have documentation available for the end users via a simple link to a pdf document.  I wondered if anyone had suggestions on how to integrate a more robust help system in a Drupal application, perhaps with search etc.  I've searched around on this topic but everything that comes up assumes I am talking about Drupal help documentation.

Interesting question, I've been asking myself about the same thing. Read on for details ...

From your last phrase, I get the impression that you don't seem to like the "Drupal Help documentation", or that for some reason it doesn't fit your needs. I'm assuming that your talking about the Advanced Help module. If not please add an hyperlink to what exactly you mean. I've been considering actually starting to USE the Advanced Help module, e.g. in the modules I maintain, such as chart, charts and visitors. E.g. because of it's integration with Drupal searches in a site, and because it's basically HTML formatted content, which should be straightforward to use for building actual tutorial contents.

I researched a bit within some of the typical modules (in core or contrib) that do come already with such 'Advance Help' tutorial pages (like 'trigger' back in D6 I believe). It took me a while to figure out what exactly to go look for where (= "what does this 'advance help' module actually add to such module that uses it?"). After I got that, I wondered "how do they do that, or what am I supposed to do in my own module to get something similar, and what kind of options/features do I have?". I didn't quite get it at first, so then I started to just scan the code of those contribute modules (using a string that I saw in the help docu from that module). Then I figured out, as often is the case in Drupal, it is a matter of knowing how to call which hook in the advanced_help module.

Next step I started to look around for "Advanced Help" about the "Advanced Help" module (makes sense I think, no?). Too bad, couldn't find any info about "how" to get this magic to work. Now 6 to 12 months later, and rather by accident, I discovered '1' (only!) community documentation page about the advanced help documentation. But you know what: on the project home page there is no (repeat: no) Read documentation link. After I discovered it, I did 2 things:

a) create issue #2445025 . More then 1 day later now ('only?' one might say ...), no reaction at all from any of it's maintainers. Last commit to this project is from late 2013. It makes me wonder about the health of this module (sorry). Haven't checked the health of the issue queue yet ...

b) While filing that issue, I was trying to understand the available docu in that (1) community docu page. I perceived it as fairly hard to read / understand, partially because of it's poor formatting. So I did as described in my PS in that issue. There is still lots of docu about that advanced help to be added. At least (I think) for a target audience like "technical writers" who might not have the skills to go figure out how to use the available hooks (something for drupal developers, but not for site builders or something similar). Yes producing docu might be boring for the experts who wrote a module (or it's most experienced users), but it is really important for a module to be successful, i.e. lots of reported installs and as few support / docu requests as possible
OK, enough about the 'help' module (wrong name! That's another module not at all related to it), I really do want to give it a try soon to get started with it in my own modules I maintain ... How about a completely different approach (which might only fit for some modules), which is "eat your own dogfood". Which is what we did in the forena module. It's a module for reporting (and charting) in Drupal, whereas it uses XHTML to actually 'develop' your custom report (report writer if you want). Here are some sample "help" pages for that module, shipped as part of the module, which you can see at work by just following the links to this demo sample:

Forena Help: if you check it out, make sure to also experiment with that "Refine Table of contents" pull down menu near the top, and see what happens if you change the (default) value for "show chapter extract" (from no to yes).
FrxTitle: That's just one (out of many) of the links you can follow on the page in the previous bullet. After visiting that link, scroll to the top of that page where it says "Including". That's (obviously) the TOC for the subitems on the selected page. With some CSS (not shown in this sample), you could eg move that "including" to the upper right corner (to make it look more wiki style).

Voilà (oeps), here you have 2 alternatives to consider. But you know what, while writing this answer I came to realise this: for somebody who is NOT looking for a module that forena is originally designed for (= reporting about all sorts of databases), forena might ALSO be consider as a possible alternative for the "advanced help" module. To proof my point: the entire set of "help pages" I described in the previous bullet, is just a matter of some (what is called) 'FRX' files. Go checkout the forena GIT repository to go look at them to see the "source" files (in FRX format) of those tutorial pages.

What was the original question again? Did I answered it?

PS 1: For anybody wondering now "how did he do that forena tutorial?", please contact me (or 'hire us and we'll teach you') ... or just read that tutorial ...

PS 2: I actually contributed most of the work for these forena tutorials as included in the most recent version 7.x-4.x. It is a complete rework of the preio release version, in which I added tons of extra content (features that were undocumented), and introduced this new navigation links, etc. When I first shared it with the module owner (David), he asked me something like ... "How did you do that! Can't believe I never thought of that myself".


Paths to images are messed up in Vagrant All the paths linking to modules, javascript, css are correct when I move a site locally and run in a vagrant environment. Yet, the image paths stored in the site come out wrong, so they are all borked.

The console in Chrome shows the paths to the images as skipping a folder. This is how the path looks: localhost/sites/default/files/img.jpg

This is how the path should look: localhost/sitename/sites/default/files/img.jpg

For some reason, Drupal in Vagrant looks for the sites folder in the localhost folder. I feel like something is wrong with the way apache is set up on my Vagrant installation. But I suppose it could be a number of things. Does anyone know?

you should add your site name to the base url in .htaccess file and uncomment the base url code.


D7 Location module proximity search I want be able to have users search for other users based on distance. I thought I did it correctly but everytime I search I get no results.

Heres what I did:

Install location https://drupal.org/project/location
Enabled location /w location entity, location search, location
taxonomy, user locations
Added location field to profile2 profile
Ran the US zipcode file that comes with the location module
Created a view to show profiles
Added a relationship to location
Added a filter of location proximity search based on zipcode and country /w a relation field_location

Every I did above was correct. I needed to have my users re-enter there location so geo-coding would be added to their profile.


How variable_get and variable_set works in drupal How do variables work? Is it as simple as using

variable_set('myvar', 'my_value');

to set, and

variable_get('myvar');

to retrieve?

Additionally, where are these variables stored, and do they have any sort of categorisation/access control (i.e. can any module get the variables set by any other module)?

Update from comment

I can see a line like $custom_theme = variable_get('admin_theme', '0');
But i cant see any variable_set('admin_theme') in anywhere in the module though .

Variables created through variable_set() and variable_get() are stored in the variables table in the database.

variable_set('myvar', 'my_value')
is used to change the value of an existing variable to the provided value, or to create a new variable with the provided value if none exists.

variable_get('myvar', 'optional_default')
is used to retrieve the value of myvar. If myvar does not exist, then it is created using the value from optional_default. If optional_default is not specified, then myvar defaults to Null.


How to structure a "many-to-many" relationship between nodes I would like to have 2 node types, Sellers and Products. Each seller can have many products, and each product can have many sellers. Also, the relationship between Sellers and Products would need to contain a price.

What would be the best way to create that relationship, making it easy to list all the Products a seller sells on their page (with prices), as well as listing all of the Sellers selling a product on their page (with prices)?

You can achieve by these two modules:
Field Collection and Entity Reference,

You can create Field Collection field (unlimited instances) to Product, the collection field (act like a wrapper) contains an Entity Reference field references to Seller, and a price field for that seller.

Some screenshot for you:


How can I trigger rerender of an element in a preprocess function? Update: My current solution is to use the Field formatter conditions module, to suppress output of the fullname field when a first name is present.  It seems like it should be very simple to replace the value of the fullname field with the contents of the two name fields and hide those fields, but my node.tpl.php file seems not to do anything now that I'm using display suite and I can't figure out how to accomplish what I want in template.php.  Some help with that would still be greatly appreciated.

Note: I would like not to create a module just for the purposes of wrangling a couple of fields.  I am still looking for an answer to this, or a solid explanation of why a module is definitely the right way to go.

I'm probably taking the wrong approach to this.  With everything I try to do, I seem to try every wrong way first before throwing up my hands and asking the internet to tell me the right way, and invariably the right way feels wrong.

Today, I'm trying to replace the value of one field in a paragraphs bundle item with the values of two others. Here is the relevant code from template.php:

function enviroscope_preprocess_paragraphs_items(&$variables, $hook) {
    $element = &$variables['element'];
    foreach ($element['#items'] as $delta => $item) {
        if ($element[$delta]['entity']['paragraphs_item'][$item['value']]['#bundle'] == 'doc_other_contrib_pb') {
            $person = &$element[$delta]['entity']['paragraphs_item'][$item['value']];
            if (isset($person['field_pb_doc_other_first_name']) && isset($person['field_pb_doc_other_family_name'])) {
                $person['field_pb_doc_other_fullname'][0]['#markup'] = $person['field_pb_doc_other_first_name'][0]['#markup'] . ' ' . mb_strtoupper($person['field_pb_doc_other_family_name'][0]['#markup']);
            }
        }
    }
}

I verified that the #markup element of the fullname field is updated, but everything still shows up the same. Is there anything I can do to rerender?

If I need to manipulate the text and/or display based on some PHP logic, I would do it using hook_node_view(). Implement this HOOK in you custom module. Use of this module will be like.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if( $view_mode == 'full' ){
        if( $node->type == 'YourContentType' ){
            $node->content['field_pb_doc_other_first_name'] = array(
                '#markup' => $node->content['field_pb_doc_other_first_name']['#markup'] . ' ' . mb_strtoupper($node->content['field_pb_doc_other_family_name']['#markup']);
        }
    }
}

My logic may be wrong, you need to check the $node variable inside this function for all the fields value.
The above code is just a sample code to demonstrate use of HOOK_node_view.


user/login page - no access to it I want to add a Login link in the user menu. When I give it the path 'user/login', I get the message:
The path 'user/login' is either invalid or you do not have access to it.

If I give it a path of 'user', it works.  However, that's not the path I want, because it will still be visible to the logged-in user.

If I give it a full path, http://mysite.com/user/login, it works BUT isn't hidden from the logged-in user.  Puzzling.

Any ideas?  I am pretty sure I could use a module to handle this, but it seems like overkill.

If you are using the Sub-pathauto module simply:

Disable the subpathauto module.
Add your menu item(s) for user/login.
Re-enable the subpathauto module.


No option to validate for email in drupal webforms validation I've installed both the Clientside Validation module, and Webform Validation, but there is no option to validate for "valid email" in the "Form Validation" tab of the webforms edit panel. Clientside Validation claims to validate for email - what's going on?

How should I go about adding email validation?

Currently it seems there is no such functionality, as it still sits in issue queue as a feature request. You can either:

Use plugin from feature request, it's already there in issue queue.
Use regex validator, with one of the rules you choose. Simplest "usually OK" would be \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b and you can find more at Regular-Expressions.info


Chosing the container for a form I am currently programmatically constructing a form. For that, I used the hook_form() . My form is displayed and all its functionality are good.

The problem is that it is not displayed inside the div container as it normally should be. Anyone knows how to define, maybe as an attribute, the form in this tag?

in hook_form:

$form['first_element'] = array(
  '#prefix' => '
',
  '#title' => t('First name'),
  '#type' => 'textfield',
  '#default_value' => '0',
  '#required' => TRUE,
);
$form['last_element'] = array(
  '#suffix' => '
',
  '#title' => t('First name'),
  '#type' => 'textfield',
  '#default_value' => '0',
  '#required' => TRUE,
);
return $form


Which field type should I use for a telephone number, and how can I ensure each entry is unique? I have created a field (field_telephone) to store telephone numbers like 13712345678.

Which is the best field type to use?
I also want to make sure the values for this field are unique. How can I do that?

For a basic telephone field without validation you could just use a text field, and set the maximum length to something sensible for telephone numbers in the regions you're targeting.

If you want a more advanced telephone field, check out the Phone module. There's a stable release for Drupal 6, but only a dev release for Drupal 7.

To make sure fields are unique, you can use the Unique Field module.


Dynamically modify number of columns in view, responsive layout I'm using one of the AdaptiveThemes for a site I'm working on. For the sake of simplicity, we'll say it's a site for set of webseries. On the pages for the episodes, I'd like to have a view that displays thumbnails for each of the other episodes in the series. The view will ideally be setup like Hulu. For example, here, each of the episodes is listed in a slideshow list.

Since the site is responsive, I need to have the number of items displayed change with the size of the window. So, full size might show 4 thumbs, and as the view port gets smaller, it might change to 3 or 2 thumbs at a time. How can I achieve this?

Bonus points if you can give me a hint for scrolling through the list like the hulu site, too. Would that just be an implementation of Views Slideshow?

I can't see the Hulu link, I'm not in the US, so I can't comment on the slideshow aspect.

I have used Display Suite to create my own layouts and Panels to access the responsive layouts within Adaptive Theme (AT Commerce) because Display Suite layouts are not responsive. I enabled only the core Panels module, trying to do the same with Panels got messy and Display Suite allows you to draw in fields from various sources.

There is a great series of tutorials on using Display Suite here: http://www.youtube.com/playlist?list=PL7E361A55994F1648

You can also use Flexslider to make your images responsive


Views: Display the value of multiple value field as a separate column/field? I have a multi value select list field in the content type.

In views it is currently displaying as:

title: test title
field_name: value1, value2, value3

And I want it to display it like this:

title: test title
key1: value1
key2: value2
key3: value3

Where field_name is the multi value field.
Any Idea?

In order to display the value of a field differently.

In the view, click on that particular field listed under FIELDS section. In the window that is opened select MULTIPLE FIELD SETTINGS then from there change DISPLAY TYPE to one of existing or Simple Seperator and provide * html break line br * as value of Simple Seperator.

Alternative approach:

Under FORMAT -> SHOW select Content not Fields and choose the View Mode as Full Content then by default, all the values are displayed one per column.

If you want further editing then consider reading about

Delta
Module to allow adding PHP Code so you can iterate through values
Override a template
Preprocess function for that particular field.


Change structure of block content I have a block like this:

Languages

Nederlands

English

Français

But what I want is this:

  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    Action
  </button>

Action

Another action

Something else here

Separated link

I've overwritten the locale block like this: (block--locale.tpl.php)

    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
        LANGUAGE
    </button>
    <?php print $content; ?>

But I need to change the structure in the $content variable, how can I do this?

UPDATE:

In my locale module (in /modules) I've found this:

function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

As you can see they add a class language-switcher-{$links->provider}. Now I would like to add some more classes to that.

How can I do this now in my subtheme template.php? It's like my function locale_block_view_alter isn't called for some reason. I already tried with a var_dump but no result in my browser ...

If you are not in control of the initial building of the content then hook_block_view_alter() can alter the content of any block before it is rendered.

From the API page:

Perform alterations to the content of a block.

This hook allows you to modify any data returned by hook_block_view().

To target a specific block...

In hook_block_info(), each block your module provides is given a unique identifier referred to as "delta" (the array key in the return value). Delta values only need to be unique within your module.

The variable $block is passed into hook_block_view_alter(). This variable is defined as:

$block: The block object, as loaded from the database, having the main properties:

module: The name of the module that defined the block.
delta: The unique identifier for the block within that module, as defined in hook_block_info().

So you can check what the module and delta of the block to target specific blocks.


How to programmatically create a node when a payment is successful I have a content type, and  with the help of the UC node checkout module, I am able to successfully add the content to cart once it is created by the user. When the user checked out and had made a successful payment, I want to create another node of another content type.

function gy_mod_uc_checkout_complete($order, $account) {
  if ($order->order_status == 'payment_received') {
    exit();
  }
}

The above is not getting fired; I always get it as "in_checkout." I tried doing it using the Paypal sandbox.

Does anyone have a suggestion on how I should write the code I need?

Looks like hook_uc_checkout_complete() is called while the order is still in "in_checkout."

You might want to consider using Ubercart's Conditional actions module and add an action for "Trigger: Customer completes checkout"; it allows you to execute actions based on a range of conditions. You can then either execute custom PHP code to create the node, or implement the hook_ca_action() (see "ubercart/ca/ca.ca.inc" for reference).

As to how to programmatically create a node, you can either use node_save() or drupal_execute(). There's quite a few tutorials around that you can use as guidance.


Allow the user to permit per role to view of any/all profile2 fields I have a Drupal 7.0 social site with three roles, each with a profile they may or may not want other roles to see all/part of. I'm not sure how to allow the user to specify which fields can be viewed by each role, but this is my current idea:

Create an on/off checkbox to signal view permission for each role per profile field
Use the views module to present profile, filters allowed view of each profile field
Similarly, when editing a profile, it will be presented with a view module so that corresponding role permission checkboxes can show next to it.

I imagine 'edit profile' could look similar to Drupal permissions (except under permissions would be the profile fields instead of module/feature list):

I'm clear on how to set up the view such that any given role can see each profile field that has been checked.

But is this possible to make it so when the user is setting up their profile, they see a view to add/edit profile2 with inline permission boxes instead of the default profile form that hasn't any such checkboxes?

Perhaps I would need customize adding in hook_form_alter or can this all be done in the UI?

Instead you can try Profile2 Privacy module, It will do your requirement exactly.

  This module extends Profile 2 by allowing administrators to create
  privacy levels as predefined groups or sets of profile fields on a per
  role basis. Users can then select from among the privacy levels to
  apply access control to their profile.

  For each role, select the profile fields that are visible to users in
  that role, when the profile owner has selected this role. For example,
  if you created an “authenticated users only” privacy level, you might
  set the anonymous role to view first and last name fields, the
  authenticated role to see first name, last name and contact fields
  and an admin role to see all fields.


Get entity id in hook_form_BASE_FORM_ID_alter() I am working on porting a D7 module to D8.
As in Drupal 8 all things are represented as entity, menu items are also represented as entity.
Now I added a hook_form_BASE_FORM_ID_alter() implementation to alter the menu creation and edit form. On the menu edit form, I want to get the entity ID of the menu that is currently being edited.

I tried to get the entity id ID with the following code, but I am getting an error. (See line 43.)

$entity = $form_state['controller']->getEntity();

For above snippet I followed https://www.drupal.org/node/1734556.

How can I get the entity ID?

That CR is outdated, probably there's a later CR updating it: now you should use $form_state->getFormObject()->getEntity().


Append a Drupal form table For the past few days I have been trying to update a rather simple table with ajax.  The table cannot be rebuilt.  This is of my own accord, if the table is rebuilt all of the colors data that was already put in is ruined.  The table must remain unchanged, only appended on.

Drupal's append does not seem to give me this functionality.  Even if I set up the form and theming properly the big issue is that on submit the node will not recognize the new data.  It only accepts that which was built on start and my appends although showing up on the screen do not show up at all on submit.  Each input is not named either despite being put in.  I cannot figure out what is going on here.  This is just a mess...  Please help.

IN HOOK_FORM

$form['recipe_ingredients']['recipe_more_ingredients'] = array(
    '#type' => 'submit',
    '#value' => t('More ingredients'),
    '#description' => t("If the amount of boxes above isn't enough, click here to add more ingredients."),
    '#weight' => 1,
    '#submit' => array('recipe_more_ingredients_submit'),
    '#limit_validation_errors' => array(),
    '#ajax' => array(
      'callback' => 'recipe_more_ingredients_js',
      'wrapper' => 'thistobe',
      'effect' => 'fade',
      'method' => 'append'
),
);

function recipe_more_ingredients_js($form, &$form_state) {

    $form['recipe_ingredients']['ing'][$id] = array(
        '#theme' => 'ingredients_row',
    );

    $form['recipe_ingredients']['ing'][$id]['quantity'] = array(
        '#type' => 'textfield',
        '#title' => t('Quantity'),
        '#size' => 8,
        '#maxlength' => 8,
        '#attributes' => array('class' => array('form-item-recipe-ingredients-quantity')),
);

  return $form['recipe_ingredients']['ing'][$id];
 }

All changes to form must be done through hook_form.  Adding a new form in a js callback function will not be accepted as new elements to a form in Drupal.


Is it Possible to Change "Edit Permissions" Based on a Field Value on that Node? I have users that need to be able to edit a piece of content they created until the status field on the piece content is updated to a particular value.

I've done some research and it looks like there are questions that are similar to mine but different enough that their solutions don't seem applicable.

I realize this question might be vague but I don't know how else to phrase it.

Are there any solutions to my problem?

Edit: I am using Drupal 7.

I think you can achieve this by implementing hook_node_access() with a check on the particular field.

https://forumone.com/ideas/programmatically-restricting-access-to-drupal-content has a very similar use case (except the field there is an entityreference field to users, but you get the gist)


How do I create a new Slideshow in the header? I've inherited a site with a functioning Slideshow. I haven't been able to figure out how that appears on the site. And I'd like something similar to the functioning Slideshow in the header and have been unable to get that to work. The functioning Slideshow is comprised of:

A Panel Node with content:

View: Slideshow: Slideshow Block
Welcome Message Block
View:Featured Articles: Featured News Block
Home page mini

None of the objects, that I have been able to find, are set to appear (any place I can find), yet the home page shows all the appropriate stuff.

I've tried creating a new Panel Node with all the same content and it doesn't appear. I've tried creating a New Slideshow Block and putting it in the Header Region and the first image appears without rotation.

I'm confused and would appreciate some guidance.

This is just a guess since the information provided is very limited: Often slideshows in the header are output as background images on the theme level. So maybe you should have a look at your page.tpl.php (and maybe also your template.php) to see if at some point the view is called from there and not from the panel.


Auto increamented field in webforms I need to create a auto generated number in web forms. I have used serial module for this but its working on webform in content. Please help me how i can do this.

Create a custom module and alter the fields value using hook_form_alter()

<?php

function pahcom_form_edit_module_form_alter(&$form, &$form_state, $form_id) {
    if($form_id =='formid) {
        $new_value = rand(100000,10000000);
        $form['submitted']['vendor_id']['#default_value']=$new_value;
        //$form['submitted']['vendor_id']['<h</h4>default_value']=$new_value;
    }
}

?>


hook_menu() item is not showing in primary-links even it exist in menu_links and menu_router tables I'm using hook_menu() in my module which defines a menu item in the primary-links.

I flushed the cache and refreshed the modules page but the item didn't show in the primary-links.
I checked the menu_links and menu_router tables and the item was defined it them.

function mymodule_menu() {
  $items['newuser'] = array(
    'title' => 'Register',
    'menu_name' => 'primary-links',
    'page callback' => 'register_browse_page',
    'access callback' => 'newuser_access_callback',
  );

  return $items;
}

function newuser_access_callback() {
  global $user;

  if ($user->uid == 0 && user_access('access content')) {
    return TRUE;
  }

  return FALSE;
}

function register_browse_page() {
  $form = drupal_get_form("newuser_form");
  return theme("newuser_form_page", $form);
}

What is the problem? How do I fix it?

This condition in your newuser_access_callback tells to your link to shows only to anonymous.

if ($user->uid == 0 && user_access('access content')) {

If you want see it as admin also, you should add yourself like that

if ($user->uid == 1 || ($user->uid == 0 && user_access('access content'))) {


Views filter criteria multiple content types (Drupal 7) I have created a view and added the filter criteria content type. I have chosen two content types. They are both being displayed. I would like then further filter one of the content types so that only those which have had a check box selected will display. Is it possible to do this in views?

Thanks,
JP

This can be done by modifying the Views filter criteria.


What is the correct way to render content from custom content type? I am new to Drupal and am realising that there are a number of ways to perform even the most basic task but it is hard to know which way is right.

When rendering fields from a custom content type which of the following ways is correct/most efficient/safest way or am I wrong and there is another even better way?

Option 1 - this way seems a little verbose but I have read in a number of places that this is the correct way to render individual fields.:

<?php $included = field_view_field( 'node', $node, 'field_what_s_included', array('label' => 'hidden') );
            print render($included);
        ?>

Option 2 - This way seems much neater and is also written about a lot:

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

Thanks for clarifying this for me.

James

Option 2 is the preferred option.

Use the default node.tpl.php as a reference.

You can see it uses the hide() function to hide fields it doesn't want to render and the render() function to render fields.

This is because all the processing you are doing in option 1 with field_view_field() has already been done and is ready to render, so you don't need to do it again.

I recommend doing some reading on overriding themeable output, which involves overriding markup with theme functions and template files.


Editable fields in views I am hiding a field using hook_form_alter, because I only want to be able to edit this field in views. then, I used the Editable Views Module to display this field. Now, my problem is that when I press the save button, all of my nodes are saved.

Is there any way to only save nodes where this field has been edited?

Seems you're looking for the jEditable inline content editing module. I tried this module for one of my project and working fine.

Using this module you can do inline edits for individual fields. you can make inline edits at node output and views output too.

Note: Right now There is only dev version available  for Drupal 7x so make sure to install and test on local instance first.


How do I use PHP in "Rewrite results" for a field in a view? In a view, I configured a file to "Rewrite the output of this field." In the text area I need to use PHP. Can this be done?

No, it cannot be done. You can write HTML code in the rewrite box. Please take a look at this if you need to write php code in Views: Views Custom Field
Although I would suggest you create a template to add any custom php code you require.


Ckeditor strips  tags CKeditor strips the <i> tags, and I can't find where in config.js I can put this code.

CKEDITOR.dtd.$removeEmpty['i'] = false

This is a solution for Drupal 7 and the CKEditor module.

Add an empty space -

<i class="fa fa-drupal">&nbsp;</i>


Open Atrium 2 or Drupal Commons or Simple Drupal with OG What will be the best option to build a fully functional social collaboration and community website in Drupal? Open Atrium 2 or Drupal Commons or new install of Drupal 7 with Organic groups?

I am good in Organic groups but redoing everything will be tricky though considering already existing distributions like Open Atrium and Drupal Commons.

Drupal Commons has a terrible track record or maintainability and upgrade path.  I only recommend using Drupal Commons or Open Atrium when they fit your needs out-of-the-box.   If you have very custom needs, definitely go with a custom D7 & OG build.

If you find that Drupal Commons or Open Atrium have features that you would like to replicate, then install them somewhere else and use them as a guide for creating your own features.

The best answer is to say you need to try them all and determine their strengths and weaknesses according to your project, but from personal experience, I have regretted every project I've used Drupal Commons on, and won't do it again.

One project I did, we started with Drupal Commons, and eventually realized that it was not a good fit.  So we just copied all the features we wanted into a normal D7's sites/all/modules directory.


Conditionally assign a custom role on user registration I've written a custom module that uses hook_form_alter() to set some default values from GET-parameters when the user registration form is called with certain GET values. That is, if you call mysite.com/user/register?firstname=Derp you'll find that the form field "Firstname" is magically filled with "Derp".

Now here it comes:
When a specific GET value is given, then and only then I'd like to automatically assign an existing custom role to the new user. That's not to be achieved with Rules and the like. (Yes, I know that anyone with even small insight in programming may exploit this to get the role, but the role is not really important).

I've tried to update the register form values with:

$form['#user']->roles[] = 'customRole';

A var_dump($form) gives:

    ["#user"]=>
  object(stdClass)#111 (4) {
    ["uid"]=>
    int(0)
    ["hostname"]=>
    string(14) "myhost"
    ["roles"]=>
    array(2) {
      [1]=>
      string(14) "anonymous user"
      [2]=>
      string(9) "customRole"
    }
    ["cache"]=>
    int(0)
  }

...but it seems that this data gets sorted out during the processing of the form. Thus the role is not assigned.

Alternatively I could assign the role directly using user_multiple_role_edit(), but I need the uid for that, which in turn is assigned during user_register_submit(). That function however seems to be beyond the reach of any API function I've found so far.

I'd be glad to read about your thoughts how I could assign the role on registration (to say it again: Rules doesn't do the job). Thank you.

You need to use hook_user_presave. like below,

function mymodule_user_presave(&$edit, $account, $category) {
  if ($account->is_new) {
    $roles = user_roles(TRUE);
    $rid = array_search('Test', $roles);
    if ($rid != FALSE) {
      $edit['roles'][$rid] = 1;
    }
  }
}

Replace the Test with your role name. $account->is_new will be set to 1 during the registration process alone, so your code will not execute when a user updates the profile.


How is AJAX attached to exposed filters? I am currently rendering a view manually like so:

$content = \Drupal::service('renderer')->renderPlain(views_embed_view('user_admin_people', 'page_1'));

Then I'm sending the html to the page and inserting it into a div with javascript.  I needed to use renderPlain() rather than render() because when I was doing that, I was getting this error:

  LogicException: Render context is empty, because render() was called     outside of a renderRoot() or renderPlain() call. Use renderPlain()/renderRoot() or #lazy_builder/#pre_render instead.

Now, you're probably thinking, why don't you just use render arrays normally and let Drupal handle it?  Unfortunately, I can't do that, I need to render the view's html and send it to the page, which I have already done.  BUT, when I do this, clicking on 'Filter' brings me to the /admin/people page of the Drupal site (on which it will do ajax filters properly, because it rendered from a normal render array).

How could I attach the javascript to this view html so that it reloads its data via ajax instead of linking me to the view's page?  I have already tried Drupal.attachBehaviors(), thinking that it would run something from ajax_view.js from views (which is a confusing & large file).

Or, where would I look in core to find out more about this, or where is some good documentation to read?  Am I looking in the right place in core, looking at ajax_views.js?

Still early rendering should be avoided whenever possible. Did you try to return the unrendered view in an ajax command?

  $view = views_embed_view('user_admin_people', 'page_1');
  $ajax_response->addCommand(new HtmlCommand('#wrapper', $view));

If you use the unrendered build array all the things you've described in the question like reattaching drupal behaviors, js, and css are handled by the ajax implementation in drupal, on the server side when assembling the response and on the client side when processing the incoming json data.

For this to work you also need to enable the option "Use AJAX" in the view user_admin_people, otherwise the "Filter" button rebuilds the form on a new page, which then happens to be the admin page.


How do I apply Tokens to a View? I have a list of car models from a database. I want to make a View that filters these by make, based on tokens. Eg for the token [cars:make].

I already have the tokens setup, but would anyone know how to actually use these as filters in a View?

it may be posible with a node view, not with tokens, with field values: contextual filter, nid from url, provide a default value, php code, like:

  $node = menu_get_object();
  if ($node->type == 'cars')
  {
         $mynodefiield = node_load($node->nid)->field_car_make[und][0][target_id];
      return $mynodefield;
  }

note: [target_id] is if field is an entity reference (node or taxonomy);

that view will return only nodetype=cars, and your token [cars:make] that have the same value as field_car_make.

sorry, i do not know how to do it with tokens, i hope it helps.


How to set node default language (or avoid language neutral) without Content translation module I both have nodes that need to be translated (using Entity Translation), and nodes that need to have a single language (which we are discussing here).

Because of some incompatibility between Entity and Content translation, I cannot enable "Content translation" and "Multilingual content".

Also, even if it was possible, all I really want is not linking translations of different nodes and the other features that come with Content translation.

I just want to let users select the node language when creating/editing a node without having the "Language neutral" option, or select language by default (based on current page language).

You can enable i18n_node module that is included in i18n module. Then:

Go to edit the content type (admin/structure/types/manage/page).
Open the 'Multilingual settings' tab.
Check the 'Require language' checkbox.

Done.


How to get the product id on hook form alter I am currently working on drupal 8 commerce. I need to form alter some of the expose fields but need to get the product id first so I can get my condition on the product fields. I used this kint($form_state) on my form alter to show the attached image. But when I try use this $form['storage'] im having wsod. Thanks

If You alter 'Add to card form', try this code

$form_state->getFormObject()->getEntity()->getPurchasedEntity()->product_id->getString();


drush sql-sync error: [mysqldump: command not found] I have a production server set up in my drush aliases as @prod, and a UAT server set up as @uat. I am using MySQL as the database of my Drupal sites. I can successfully execute drush command like drush rsync @prod @uat. However, when I execute

drush sql-sync @uat @prod

Error prompts:

bash: mysqldump: command not found

After googling, the solution is to set the $PATH to include /usr/local/mysql/bin, however, I do not have right to install MySQL client.

Here I have 2 questions:

Is it a must to have mysqldump in order to run drush sql-sync?
If so, apart from installing MySQL client, is there any other way to do it?

Thanks.

Looking at the drush github repo, mysqldump appears to be a
non-negotiable dependency. More broadly speaking, given it's
functionality, I'm unclear why it wouldn't be. So, yes, drush
requires mysqldump for mysql exports.
There's always another way, or expressed without my opinion; "yes." Whether it is a good practice to MacGyver such a solution depends on how much free time you have. There's an interesting php implementation of mysqldump discussed here, but here's where my caveat becomes more clear. Check out the commit activity page — not bad, but on the sparse side for a production solution for my tastes and capacity. So the answer may really depend on how much of this development your client is willing to absorb.

Personally, I'd either convince my sysadmin to allow mysqldump (something I haven't had to do in years) or move my site to a host that will provide such a basic service.

ps: I may be wrong but the Backup and Migrate may give you mysql export capability without mysqldump.


Vagrant Drupal Development (VDD) Up Stalls I'm trying to figure out why vagrant is stalling. I installed VirtualBox 4.3.12 and Vagrant 1.6.2, and then grabbed Vagrant Drupal Development (VDD) environment. When trying to bring the machine up it will immediately stall, stuck on: default: Verifying Hyper-V is enabled...

==> Default: Verifying Hyper-V is enabled...
INFO subprocess: Starting process: ["c:\\Windows\\System32\\WindowsPowerShell\\
v1.0\\/powershell.EXE", "-NoProfile", "-ExecutionPolicy", "Bypass", "&('c:\\Hash
iCorp\\Vagrant\\embedded\\gems\\gems\\vagrant-1.6.2\\plugins\\providers\\hyperv\
\scripts\\check_hyperv.ps1')", "-ErrorAction", "Stop"]
DEBUG subprocess: Selecting on IO
DEBUG subprocess: stderr: The term 'ConvertTo-Json' is not recognized as the nam
e of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At C:\HashiCorp\Vagrant\embedded\gems\gems\vagrant-1.6.2\plugins\providers\hype
rv\scripts\check_hyperv.ps1:10 char:38
+ Write-Output-Message $(ConvertTo-Json <<<<  $result)
    + CategoryInfo          : ObjectNotFound: (ConvertTo-Json:String) [], Comm
   andNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

DEBUG subprocess: stdout: ===Begin-Output===

===End-Output===

Hah! I simply added c:\Program Files\Oracle\VirtualBox to my PATH and all is well. I guess it was wanting to use vboxmanage command. I'm happy now.


Settings contains a dot which is not supported, but module gets enabled properly I'm developing a search engine module for Drupal 8.

On a clean new Drupal website, I can install it from the admin GUI, but when I enable it I have the classical white screen (The website encountered an error ...).
Checking the error.log yields the following :

  Uncaught PHP Exception Drupal\Core\Config\ConfigValueException: "gref.settings key contains a dot which is not supported." at /var/www/html/core/lib/Drupal/Core/Config/ConfigBase.php line 211, referer: http://10.113.101.197/admin/modules

But, if I go back to the website, the module is installed properly, and no further issue is reported (even when uninstalling the module).

Here is my configuration :

- config
  - install
     - views.view.grefsearch.yml
     - search_api.server.grefserver.yml
     - search_api.index.grefindex.yml
     - gref.settings.yml
     - gref.schema.yml
     - facets.facet.grefother.yml
     - block.block.gref.yml

And here is gref.settings.yml

gref:
  page_title: 'Gref Search'
  source_text: 'Lorem ipsum dolor sit amet'

Any ideas why I have this error ?

Okay, classical scenario, 30 seconds after I open a bounty for the question, I find the answer myself ...

I was looking into the wrong file. I started the skeleton of my module by following this tutorial.

In the "Basic Structure" section of the tutorial, dots are used in keys for the .schema.yml file. It is actually forbidden to use that, but the tutorial said you could anyway.

/config/schema/loremipsum.schema.yml :

loremipsum.settings:
  type: config_object
  label: 'Lorem Ipsum settings'
  mapping:
    loremipsum:
      type: mapping
      mapping:
        page_title:
          type: text
          label: 'Lorem ipsum generator page title:'
        source_text:
          type: text
          label: 'Source text for lorem ipsum generation:'

I removed the dot at the key, and the problem disappeared.


Creating a Drupal user with user_save doesn't automatically join an existing CiviCRM contact record I have a custom module that will create a Drupal user programmatically using user_save as follows:

  //set up the user fields
  $fields = array(
    'mail' => $email,
    'pass' => $password,
    'name' => $username,
    'status' => 1,
    'init' => $email,
    'access' => REQUEST_TIME,
    'roles' => array(2 => 'authenticated user'),
  );

  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);

I have first done a check using the CiviCRM API to make sure that if an existing contact is already in the database and has a Drupal account associated with it, we don't create a new one. Also I check to make sure the email address isn't registered from the Drupal side.

The problem is, when I create a new user, it is not linking up to an existing CiviCRM contact record that uses the same email address and I'm ending up with a duplicate contact record.

How can I force the site to link to an existing record if the email address is a match?

The function to synchronize Drupal users and CiviCRM contacts is CRM_Core_BAO_UFMatch::synchronize().

Since you're calling user_save(), CiviCRM's hook_user_insert implementation should get triggered (from user_module_invoke('insert', $edit, $account, $category); in user_save().

CiviCRM's civicrm_user_insert() checks whether it thinks you are on a CiviCRM callback already*, then calls either civicrm_register_data() which will in turn call CRM_Core_BAO_UFMatch::synchronize(), or CRM_Core_BAO_UFMatch::synchronize() directly.

To deal with this you could trace your way through CiviCRM's code (drupal/civicrm.module, drupal/civicrm_user.inc, CRM/Core/BAO/UFMatch.php) and work out which path your code is triggering; ultimately you want to end up with a call to CRM_Core_BAO_UFMatch::synchronize() which passes in the parameters for CiviCRM to correctly match the existing and new data.

You could also just call that function directly from your custom code; that might be less robust as in future you might end up triggering the synchronize call twice ...


Programmatically rendering a Views pane with arguments from context I'm trying to programmatically render a Views pane (ie. a Pane display of a view) with a taxonomy term as argument (passed in the pane context)

The following code illustrate how the pane is rendered

$selected_type = 'views_panes';
$selected_subtype = 'persona_display-panel_pane_1';
$context = array(
  'context_taxonomy_term_1' => ctools_context_create('entity:taxonomy_term', $fully_loaded_taxonomy_term);
);
ctools_content_render($selected_type, $selected_subtype, array(), array(), array(), $context);

It mostly works and the view is rendered. However, the taxonomy term in the context is not used as argument for the view.

In the pane views display's settings, the "Argument input" for the one views' argument is configured as "Term ID" "From context":

I looked at the code for the view display handler. Arguments handling is done in views_content_plugin_display_panel_pane::pane_process_conf(). I checked there and the issues seems to be that $conf['context'] is not set. So $context_keys ends up being an empty array. Later in the switch statement, $key = array_shift($context_keys) sets $key to NULL, the isset($contexts[$key]) test fails and the $argument is ignored.

I have no idea if this is a bug with Views pane, or if something is missing in the pane rendering code.

Note: I'm actually using a Pane Field field in a Paragraphs bundle.

I got it to work with

$selected_type = 'views_panes';
$selected_subtype = 'persona_display-panel_pane_1';
$context = array(
  'context_taxonomy_term_1' => ctools_context_create('entity:taxonomy_term', $fully_loaded_taxonomy_term);
);
$config = array(
  'context' => array('context_taxonomy_term_1');
);
ctools_content_render($selected_type, $selected_subtype, $config, array(), array(), $context);

So, in order to render a Views Pane display with contextual filters coming from the pane's context you to populate $context and inform the display handler on which entries of $context to use for each contextual filter with $config['context'].


How do I programmatically set contextual filters? I need to set a contextual filter programmatically and almost every view I have will have this filter. However, some wont and will have other contextual filters instead.

I have tried following the examples in here but this will just set the first argument to be my filter value regardless of what field is it for.

In views_pre_build I get the keyed arguments list under $view->argument and can do ->setArgument() but this doesn't change the set of results.

Is there an easier way of setting a specific contextual filter?

Contextual filters use query string params.  You could hard code these into the URL.  If using a Url object, you can pass a third argument ['query' => ['param1 => 'param1_value',...]].  Try setting a filter and seeing what the URL param name & value is after doing so.

In hook_views_pre_build(), you can also set the filter value directly:

$view->filter['filter_name']->value = 'filter_value';

It's helpful to have Xdebug so you can see the names of existing filters.  If you don't have xdebug, try finding the correct filter name in the ->filter property, then find the desired filter value, and put 2 and 2 together.


A referenced node is missing--when did it disappear? So, I inherited a long-standing and complicated drupal site with a lot of records that reference each other. The site started out in Drupal 6 and these references used to be CCK Nodereferences, but they ported to Drupal 7, and I think things are now mostly entity-references, though there might be a CCK Nodereference here or there.
I'm mentioning this because it's an area that I don't know much about and I think it might be relevant for what follows.

The problem is this:
There are some nodes that are referenced by ID by other nodes that seem to have disappeared. Let's say, for example, we have a content type "Chicken coop", which contains references to 100 "chicken" nodes. If I edit "Chicken coop", I'll see 100 fields, each with a name and value, for example, "Hen 1[nid:1]", "Rooster 50[nid:62]" but one of them will be a null reference. "[nid:4]", and when I build a view to list all the "Chickens", there will be no chicken with nid:4. It's like that chicken got removed from the database and removal didn't propagate to all the things that referenced it like it should have.
Obviously, I'd like to know how this happened, and I've noticed that we have had backups turned on for several years. I'd like to find out when this happened and what other things happened around this time. Did these null references appear at the same time?

I can download the backups and load them into a local mysql instance. How would I query to see if chicken nid:4 is still in them? This does not seem simple or intuitive from the drupal schema I've seen.
Does this problem seem familiar to anyone and do you have any suggestions on whether this was a one-time thing that's not likely to happen again?
Any other logs that you would recommend examining or troubleshooting steps I ought to take?

Drupal 7 does not delete references to deleted nodes by default. See the Field reference delete module. Some details about it, from its project page (check that page for even more details):

  This module removes references to a deleted entity from fields stored in an SQL database. It exists to prevent stale references to non-existent content from causing unexpected problems (for example, when the referencing content is being displayed).

I'm not sure if it will clean up existing "dead" references, but at least moving forward it does.


How to override page.tpl.php with view's template file I am using D7 and view3 (beta). I created a view named employee with a template for the field first_image, views-view-field--employee--page--field-first_image.tpl.php. When I rescan the theme information, this template became bold. It worked fine (When clicking the image, a slim box will show).

But I inserted this view in a basic page using insert view2.x dev module with tag [view:employee]. But this time my template file doesn't show and seems to be broken. How can I solve this?

First you define a specific display in your template: views-view-field--employee--page--field-first_image.tpl.php.

Then you don't specify a display in your insert tag, making it fallback to default.

To fix your problem you need to either strip the display part of your template name or specify a display in your tag, like [view:employee=page].

I would probably go for the first solution, so your theming targets all possible displays of that view, but how you do it really depends on your implementation.


How do I separate multiple values for "print render($content['field']);" with a comma? So in my node template, I am using the following code:

print render($content['field_taxonomy']);

Sometimes there is only one result printed, and sometimes there are multiple results printed. How can I separate each result by a comma, but only if there are multiple results printed?

Thank you!

For example, I am fetching the texonomy vocabulary terms :

$terms = taxonomy_term_load_multiple(array(), array('vid' => '12'));
foreach ($terms as $temsaccess) {
$name[]=$temsaccess->name;
}

<a href="javascript:void(0);" id="<?php echo $term_name; ?>" Click="javascript:showProduct('<?php echo $term_name; ?>', this );"  data-filter="<?php echo $temsaccess; ?>">
<?php echo $temsaccess; ?>
</a>

Or refer to this link.


templates, products and teasers I do not really know where to look anymore. I'm using D7 and Drupal Commerce and I would like to display a block using a rendered entity. I created my node--product-display--new-teaser.tpl.php and everything works fine, until I try to load a field from the related product: field_images.
The difference is that in the default version field_images display using an imagezoom, while the new node: new-teaser (that I have created under product display) only display the first image.

What I would like to do, is to render in my node--product-display--new-teaser.tpl.php the field_images coming from the node: new-teaser new product display mode.

There is a way to do what I am trying to do:
in your product_display display mode, in your product field, you chose: rendered entity, and in rendered entity options, you will be able to select your new product display mode.

I hope this helps somebody.


Use db_select with multiple conditions of which one needs to apply My question is not a duplicate and it has complex conditions. Please let me explain. In my second condition, first I need to check if number value is correct (in first condition I checked complete opposite). If so, then check if there's a value in email column. Then show error message if there's a value in email column. My problem is I need to write first query (already done by me) and second query under the same 'db_select'

Checking for email value only activates if webform value matches a value in 'number' column.

I have a table containing two columns namely, 'number' and 'email'.

I need to run a db_select query to display same error message when a webform is submitted. My conditions are as follows:

Show error message if number value provided by webform does not matches a value in 'number' column
Show error message if number value provided by webform matches a value in 'number' column but corresponding 'email' column is not empty.

So far I'm able to show error message for the first condition.

db_set_active('mydatabase');
    $query = db_select('mytable', 'c');
    $query->fields('c', array('number','email_address'))
    ->condition('number', $phoneval, '=');
    $result = $query->execute()->fetchAll();

if (empty($result))
{
    form_set_error('phone_number','We have no record of that Assessment Number');
}

How can I show the same error message for condition 2? I don not want to query the database again and thinking of using for db_or this.

Thanks

Syntax for db_or :

$or = db_or();
$or->condition();
$or->condition();
$query->condition($or);

For More Information


I need to pass a node id to a block I am open to doing that with hook_ module code (since i'm doing all my work in a custom module), and I'm open to doing that with Panels, which I'm using.  I don't want to add PHP in the admin interface.

Thanks in advance.

Not quite a block, but you can do this with custom panel panes and pass it the $node being viewed.  This is the cleanest way.  I don't have a link handy for an overview on how to do this, though.

You can also do something similar using a view, and wiring up the relationships / arguments appropriately.  You can then stick this view into a panel pane.

The hack is do do something like this in your block code

if (arg(0) == "node" && arg(2) != "edit") {
  $nid = (int) arg(1);
  if ($nid) {
    // do stuff
  }
}


D7: using a list-based field for views Stumped. This should be Drupal 101, but the dots aren't connecting.

Scenario: from among many, I have two content types:

employee
department

Each content type displays on its own but we will also run a list of employee teasers as a  list within a views block on the department pages. This is easy to create: I use views to render the list, i.e.,

View uses filter criteria of "department" for a teaser list of employees.

Set the views block to display on the appropriate department node page on the blocks admin page and all is good. However, I have 7 department pages. Sure I could create the first view, clone that view per required filter type, but, better, is reusable code. Both content types have the same "department" field list (uses the core list module) where I've identified the department.

How can I use that "Department" list field to create the link that joins the employee list to the department when rendering the department page?

Using Drupal 101, and assuming that you have one Department page per department, and one Employee page per employee, and assuming that each employee can be associated with more than one department ...

First add a node reference field to the Employee content type (field_department). Set it to reference the Department content type and set the number of values to unlimited.

Then create a view of Content type:Employee.

Add a Relationship on Content:Department (field_department) and make it Required.

Then add a Contextual Filter on Content:NID. Have it use the Relationship you have just created and configure it to Provide Default Value: Content ID from URL when the filter is not available.

Under Advanced > Query Settings check Distinct. This type of query might produce duplicates.

Place the View block on the Department page, and this will restrict the list to employees related to the department currently being viewed.

A similar approach can be used with term reference fields, but you would require two relationships (first to the term, then from the term to the other content type). I cannot speak about the List module as it appears to be discontinued on D.O.


Calendar widget link to list a day's events I am using the Calendar module to manage an events calendar on a new site. Currently when you click on a day in the widget it takes the user to the calendar page that shows a small list of the titles.

Is there a way to create a view that shows all of the days, and events for that day, in a single spread and bypasses the calendar completely?

I have got it: If you go to the Day view under the Calendar view, you can change the format to HTML list and show fields. From there, add the fields of the calendar event you want to show.


difficult to understand drupal hook menu function I am new to drupal.I can't understand how drupal hook menu works.I visit the drupal site and try to read documentation.but it is too difficult to understand.can you please tell me a good tutorial so that I can understand how they work.thanks in advance

For me the best way to get a solid understanding on Drupal quickly, was to purchase some video tuition. By watching just a couple of these paid downloads, I had a good understanding on the basics.

Most tutorials step you through building your first custom module, explaining what everything is, why it is required and how it works into the overall structure.

A number of companies offer this type of product, and this one is a freebie from one site to introduce the Drupal menu system, including hook_menu()


Create custom path alias when new user is added in drupal 7 I've created contents using custom form. I don't use content types. I could add, update and delete that content by access test, test/id/edit and test/id/delete.

I've displayed content lists for a user by tests/uid. Now I want to use user name instead of uid. I have to replace space by '-' and also replace all special characters. So my choice is both url alias and path auto.

But I couldn't add custom url pattern into pathauto pattern. There is only available for content types, taxonomy term, user and file path. But I want to custom url pattern for custom content inside the user path.

If I understand your question correctly, you're wanting to implement Pathauto's API. Here's a tutorial on how to do so. Basically, you need to implement hook_pathauto() and make use of pathauto_create_alias() & path_delete() when you're performing your Create/Update/Delete operations. It looks like you can use the token_type of user for your token replacement.


How do I theme the user register page? In Drupal 7, we can use a template file like page--user--register.tpl.php, or we can register our own template file.

How we can do it in Drupal 8?

This is similar in D8. Copy page.html.twig from core or base theme and put it into the template directory of your theme.

Rename it like this:

page--user--register.html.twig


How to edit vocabulary machine name? I migrated my site from lower version of drupal, during migration process the machine name of my vocabularies was changed, now I want to modify them manually, but I cant find the proper table in database. now the question is :

  How can I edit vocabularies machine name manually?

Suppose that the machine name of your vocabulary is: test.

Then you can use the following code

$vid= 'test';

$vocabulary= taxonomy_vocabulary_load($vid);

$vocabulary->set('name', trim('newmachinename'));

$vocabulary->save();

  change the newmachinename by your machine name.

Note. you must be careful when using this code, because those configurations that you have with the previous machine name will be affected


Using migrate with a multi-page / paginated source I have a working module pulling a JSON feed into Drupal using the Migrate module. However, the feed is paginated, and I am only getting the first page of results (ordered DESC on creation, so giving the latest items).

I need to go back through all pages and get all/any changed items, but I can't see how to tell Migrate to iterate through the pages.

You can parse paginated sources with migrate but it takes a little work overriding MigrateListJSON - you may want to ignore the $jsonContainer part - that's just because the result set in our service is in a container (hence this class is abstract).

abstract class BSBaseMigrateListJSON extends MigrateListJSON {
  /**
   * String containing the JSON container name.
   */
  protected $jsonContainer;

  /**
   * Contains the default limit for pagination of the service.
   */
  protected $serviceLimit = 50;

  /**
   * Return an array of the IDs found in the list URL.
   */
  public function getIdList() {
    migrate_instrument_start("Retrieve $this->listUrl");
    $data = $this->getTree();
    migrate_instrument_stop("Retrieve $this->listUrl");
    if ($data) {
      return $this->getIDsFromJSON($data);
    }
    Migration::displayMessage(t('Loading of !listurl failed:', array('!listurl' => $this->listUrl)));
    return NULL;
  }

  /**
   * Returns the amount of items to be processed.
   */
  public function computeCount() {
    if ($data = $this->getTree()) {
      return count($data[$this->jsonContainer]);
    }
    // Else fail and return N/A results.
    return NULL;
  }

  /**
   * Returns an array of crids.
   */
  protected function getIDsFromJSON(array $data) {
    $ids = array();
    foreach ($data[$this->jsonContainer] as $item) {
      $ids[] = $item['id'];
    }
    return $ids;
  }

  /**
   * Returns the list URL decoded JSON response.
   */
  protected function getTree() {
    $items = array();
    $offset = 0;

    do {
      $url = $this->rebuildUrl($offset);
      $json = $this->getTreeData($url);
      $data = drupal_json_decode($json);
      $items = array_merge($items, $data[$this->jsonContainer]);
      $offset += $this->serviceLimit;
    }
    while ($data['moreResources'] == TRUE);

    // Return data if any is present.
    if (!empty($data)) {
      $data[$this->jsonContainer] = $items;
      // @todo Consider whether just returning $items is feasible.
      return $data;
    }

    Migration::displayMessage(t('Loading of !listurl failed:', array('!listurl' => $this->listUrl)));
    return NULL;
  }

  /**
   * Returns a constructed url with offset if required.
   */
  private function rebuildUrl($offset = 0) {
    $url_parts = parse_url($this->listUrl);

    // Build the query parameters.
    if (isset($url_parts['query'])) {
      parse_str($url_parts['query'], $url_parts['qparts']);
      foreach ($url_parts['qparts'] as $key => $value) {
        if ($value === '') {
          $url_parts['qparts'][$key] = NULL;
        }
        elseif ($key === 'q') {
          $url_parts['path'] = $value;
          unset($url_parts['qparts']['q']);
        }
      }
    }

    // If the offset is zero then we can simply return the original list URL.
    if ($offset == 0) {
      // Handles overriding the service limit if there's already a limit set in
      // the list URL.
      if (!empty($url_parts['qparts']['limit'])) {
        $this->serviceLimit = $url_parts['qparts']['limit'];
      }
      return $this->listUrl;
    }

    // Add the offset to the query parameters.
    $url_parts['qparts']['offset'] = $offset;

    // Build parameters to pass to the url function.
    $url_params = array(
      'path' => $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'],
      'options' => array(
        'query' => isset($url_parts['qparts']) ? $url_parts['qparts'] : NULL,
        'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
        'external' => TRUE,
        'https' => (bool) $url_parts['scheme'] == 'https',
      ),
    );

    return url($url_params['path'], $url_params['options']);
  }

  /**
   * Returns the data from the given list URL.
   */
  private function getTreeData($list_url) {
    if (empty($this->httpOptions)) {
      return file_get_contents($list_url);
    }
    $response = drupal_http_request($list_url, $this->httpOptions);
    if (!empty($response->data)) {
      return $response->data;
    }
  }
}

This code probably won't work as-is for you as it's specific for our service, you'll most definitely need to change this line: while ($data['moreResources'] == TRUE); and anything to do with offset depending on how your service works but it's a start for how to proceed.


i18n + views, getting localized version of node I have a view, lets call this View A, which only shows nodes - that are referenced as the 'hero' node to a taxononmy (one to one relationship). Additionally, I have another view, lets call this View B which does the opposite: only shows those nodes that do not have the hero relationship with a taxonomy.

Now I have translated all these nodes with the i18n module into two languages. But when I change language on the site the following happens:

View A stays the same, only showing the content in its original languages (in the language of which the relationships were created).

View B has the same content as it had, plus the translated 'hero nodes' that are supposed to be in View A.

I kinda gather this has to do with the relationship of node ids that is being filtered. However, how can I make this work that both View A and View B will show the appropriate localized content?

Add this to your Filter Criteria: "Content: Language (= Current user's language)."


Change print icon programmically through template.php I'm using the Print module, version 7.2, and trying to change the icon through the template.php.
After researching, I have found the main functionality in the FAQ of the module, which provides this:

The example below is for the 6.x-1.x and 7.x-1.x branches. In 7.x-2.x
the theme function is theme_print_ui_format_link.
You will have to define a theme_print_format_link function which will replace
the module's function with the same name and where you can indicate your
custom-defined icon, and set the html element to true so that your
image tag is interpreted as HTML. See the following for an example:

function theme_print_format_link() {
  $print_html_link_class = variable_get('print_html_link_class', 'print-page');
  $print_html_new_window = variable_get('print_html_new_window', 0);
  $print_html_show_link = variable_get('print_html_show_link', 1);
  $print_html_link_text = filter_xss(variable_get('print_html_link_text', t('Printer-friendly version')));

  $img = local_path_to_your_img_file;
  $title = t('Display a printer-friendly version of this page.');
  $class = strip_tags($print_html_link_class);
  $new_window = $print_html_new_window;
  $format = _print_format_link_aux($print_html_show_link, $print_html_link_text, $img);

  return array('text' => $format['text'],
               'html' => $format['html'],
               'attributes' => print_fill_attributes($title, $class, $new_window),
              );
}

If I don't change the code at all, it never gets called.

If I change the first line to subtheme_print_ui_format_link() {, it gets called, but then I get the error
Fatal error: Call to undefined function _print_format_link_aux() in ...../public_html/sites/all/themes/subtheme/template.php on line ...

I have tried:

subtheme_print_format_link_aux()
_subtheme_print_format_link()
_print_ui_format_link_aux()
_print_ui_format_link()

and a bunch of others instead of _print_format_link_aux(), but error just replaces the first function with the one I tried.
Note: I have have changed local_path_to_your_img_file to 'images/print_icon.png'

blog.kalamuna.com helped me a lot. I just changed the $icon value.

Here is the code that I put in the PHP tags in my template file

//Change print icon in print icon
/**
 * Format the Printer-friendly link
 *
 * @return array
 *   An associative array containing:
 *   - text: The content of the link
 *   - html: TRUE if the text contains HTML tags, FALSE if it's plain text
 *   - attributes: several attributes of the link tag (title, class, target,
 *     onclick, rel)
 *
 * @see _print_ui_fill_attributes()
 * @ingroup themeable
 * @ingroup print_themeable
 */
function subtheme_print_ui_format_link($vars) {
  $format = $vars['format'];
  $path = '/images/print_icon.png'; //path to file, relative to theme YOUR_THEME

  foreach (module_implements('print_link') as $module) {
    $function = $module . '_print_link';
    if (function_exists($function)) {
      $link = call_user_func_array($function, array());

      if ($link['format'] == $format) {
        $link_class = variable_get('print_' . $link['format'] . '_link_class', $link['class']);

        $new_window = FALSE;
        $func = $module . '_print_new_window_alter';
        if (function_exists($func)) {
          $func($new_window, $link['format']);
        }

        $show_link = variable_get('print_' . $link['format'] . '_show_link', PRINT_UI_SHOW_LINK_DEFAULT);
        $link_text = filter_xss(variable_get('print_' . $link['format'] . '_link_text', $link['text']));

        if ($show_link >= 2) {
          // Work out which icon we want to show based on the link's format.
          switch ($link['format']){
            case 'html':
              $icon_name = 'print';
              break;

            case 'mail':
              $icon_name = 'envelope-o';
              break;

            case 'pdf':
              $icon_name = 'file-pdf-o';
              break;
          }

          // Build the icon.
          $path = '/' . drupal_get_path('theme', 'YOUR_THEME') . $path; //the path is relative to the theme 'YOUR_THEME'
          $icon = "<img src='" . $path . "' class='print-icon " . $link_class . "' alt='Print this page' />";

          // Show the icon with or without text, depending on config settings.
          switch ($show_link) {
            case 2:
              $text = $icon;
              break;
            case 3:
              $text = $icon . ' ' . $link_text;
              break;
          }
          $html = TRUE;
        }
        else {
          $text = $link_text;
          $html = FALSE;
        }

        return array(
          'text' => $text,
          'html' => $html,
          'attributes' => _print_ui_fill_attributes($link['description'], strip_tags($link_class), $new_window),
        );
      }
    }
  }
}


Images and CSS effect not showing Hello I'm using Drupal 6 and I've successfully finished with the site. However, after I uploaded the site to the server, I realised the the header image which is the logo is not showing even though the path is correct in the theme logo path.

Also there is a slide show which was made with Dynamic Display Block module and its images does not show up even though their path is present and correct.

The css style I applied to the three column under the DD Block is also not showing.

This still persists even if I change theme.

Does anyone know what's wrong under the hood?

Thank you

I think you should check the permission of "sites" and "files" folders. You cannot access to the folder.

I think something happened when you uploaded the website. Usually I do a fresh installation of drupal then I upload the files inside "all" folder and the files insidethe "files" folder inside "default". In the end through Backup and Migrate module I upload the db.

It must be a permission problem if you see the images there.

Let me know.


Changing entity base field settings Changing entity base field settings
I have a custom car entity with 8 base fields like the following:
  $fields['color'] = BaseFieldDefinition::create('list_string')
    ->setLabel(t('Color'))
    ->setRequired(TRUE)
    ->setSettings([
      'allowed_values' => [
        'Blue' => 'Blue',
        'Green' => 'Green',
        'Red' => 'Red',
      ],
    ])
    ->setDisplayOptions('view', [
      'label' => 'inline',
      'type' => 'string',
      'weight' => 1,
    ])
    ->setDisplayOptions('form', [
      'type' => 'options_select',
      'weight' => 1,
    ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

I have a requirement to allow the end user to partially change some parts of some of the base fields like order and allowed values using custom simplified forms.  I have the following code in the 'submitForm' function of a form.
  $field_definition = $this->entityDefinitionUpdateManager->getFieldStorageDefinition('color', 'car_module');
  $field_definition->setRequired(FALSE);
  $this->entityDefinitionUpdateManager->updateFieldStorageDefinition($field_definition);

When the 'Save' button is hit, the server takes a long time to respond like database changes are being made but the field definition does not get updated.

Base fields are defined in code. When code updates change the database schema you can implement the updates via entityDefinitionUpdateManager in an update hook as shown in the question. This is not possible in a form submit.
If you want to store field settings in a form submit load the field config and save it:
// if the entity type has no bundles use the entity type id:
$entity_type_id = 'vehicle';
$bundle = 'vehicle';

$fields = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions($entity_type_id);
$field_config = $fields['field_example']->getConfig($bundle);
// make changes
$field_config->save();

For form and view display settings you can use EntityDisplayRepositoryInterface::getFormDisplay and EntityDisplayRepositoryInterface::getViewDisplay:
$display_repository = \Drupal::service('entity_display.repository');
$display = $display_repository->getViewDisplay($entity_type_id, $bundle, 'default');
$display->setComponent('field_example', $display_options);
$display->save();

For both code examples if there is no configuration stored yet it will be created.

Your question is about a custom form. Instead you could expose the core field admin UI by adding field_ui_base_route to your entity, even if you don't intend to use bundles or view modes. This works also for base fields marked as configurable. See How do I add a view mode to a simple custom entity?


How to send an email once a new member is invited using the Group module? I am using the Group module on a Drupal 7 project. I would like the system to send an email notification once a new member is invited.

I'm assuming I could use the Rules module to perform this task, but so far my new rule configurations for this task is not working.

Has anyone experienced this issue and resolved it? If so please share your steps on how you achieved this.

The Group module, out of the box, does not seem to send any eMail notifications to some user who got invited to join some group. Note however that a special Drupal message is shown right after an invited user performs a login to the site (too bad if the invited user never performs a login ...). Here is a sample of such message (which includes a link to relative path /user/uid/group/invite):

You have pending group invitations. Visit your profile to see them.

However, since Group is entirely entity based, it's a piece of cake to use Rules for creating such eMails. The clue to do so, is related to the creation of a new group membership, and which corresponds to Rules Event "After saving a new group membership*". This Rules Event is one of the events added by the Group module, located with 'Rules group' (don't get confused ...) "Group membership". However, a Group membership also has a status, which can be any of these:

Active
Requested
Blocked
Invited

With the above in mind, you can create a rather basic rule to do what you're asking for. Just use the Rules UI to import the rule below (in Rules export format) in your own site:
{ "rules_notification_about_new_group_invitation" : {
    "LABEL" : "Notification about new group invitation",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "group" ],
    "ON" : { "group_membership_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "group-membership:status" ], "value" : "invited" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The user with name [group-membership:user] just got invited by [group-membership:invited-by:name] to join the group named [group-membership:group:title] (with group type [group-membership:group:group-type:label])." } },
      { "mail" : {
          "to" : [ "group-membership:user:mail" ],
          "subject" : "You\u0027re invited by [group-membership:invited-by:name] to join the group \u0022[group-membership:group:title]\u0022",
          "message" : "You\u0027re invited by [group-membership:invited-by:name] to join the group named [group-membership:group:title] (with group type [group-membership:group:group-type:label]).",
          "from" : [ "group-membership:invited-by:mail" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about the Rules Actions in this rule:

show a Drupal message, each time a user is invited to join some group, similar to this sample message (which also shows various Group related tokens you can take advantage of, such as the name and type of the group):

The user with name Demo.User just got invited by Pierre.Vriens to join the group named Using the Answers module (with group type Class).

Create an appropriate eMail, using the various (relevant) tokens, e.g. the eMail Id of the user who performs the invite (= from), and the user that is invited (=to).

Note that for some user who is "added" to a group (instead of "invited") by an authorized user to do so, such message will not be shown. That's because of the Rules Condition included: the status for the selected group is not "Invited" in that case, instead the status will be "Active".
BTW, if you'd be willing (and able) to also use the Message module, you could add an extra Rules Action to create an appropriate Message entity (like a custom log record) also. And if you'd then use the Views module to create a custom view of such Messages, you'd have a perfect audit trail of who invited who for any of your groups ...


ckeditor installation I went to the ckeditor website made a custom build of an ckeditor with the plugins I want, then downloaded and extracted it to

sites/all/libraries/ckeditor

(I previously installed the libraries and ckeditor modules)

then I went to the global configurations settings for ckeditor

admin/config/content/ckeditor/editg

For the "> Path to CKEditor * " value I entered

%l/ckeditor

which sets the location of ckeditor to

/sites/all/libraries/ckeditor

and I set the " Path to the CKEditor plugins directory " value to

%l/ckeditor/plugins

which sets the location of the plugins to

/sites/all/libraries/ckeditor/plugins

I save the configuration and flush all caches.  But whenever I go to edit a piece of content there is NO editor and NO body field at all on the page.

I can re-enter the default url used to install ckeditor and the editor will appear on the page, but of course, without my plugins. I have no error messages.  Anyone have any idea why ckeditor can't find itself?

thanks

Just a quick answer to my question for other drupal noobies making the same error as I have.  There seems to be a bit debate between installing stand alone ckeditor or installing ckeditor via durpal's wysiwyg module (convenient for installing multiple wysiwyg editors, if need that level of choice).  For more info read this.

At the risk of drawing wrath, with drupal, "more modules" = "more chances for errors and conflicts" so I am go with the stand alone ckeditor install.

First install the ckeditor drupal module, from the drupal project page.

Then, download the BASIC ckeditor script library from ckeditor.com .

NOTE: DO NOT ATTEMPT TO ADD PLUGINS AT THIS POINT, JUST DOWNLOAD THE PLAIN, VANILLA, CLASSIC DOWNLOAD. This is what caused the error above, some plugins do NOT "play nicely" with drupal.

After you have the download of the plain ckeditor script library downloaded, place into the  /sites/all/libraries/ directory, so that you end up with /sites/all/libraries/ckeditor/ckeditor.js  file structure.

Then in your drupal site go to /admin/config/content/ckeditor  and edit the "Global Settings" , so that the "Path to ckeditor" is  %l/ckeditor (sites/all/libraries/ckeditor) and the "Path to plugins" is %m/plugins (sites/all/modules/plugins)

NOTE: By default ckeditor points to a web address (CDN) for the "path to editor" value, which is mighty inconvenient if you work offline on a local dev server without internet from time to time.

Save Configurations

Assuming your install was successful, meaning that you did not have any red text drupal messages at /admin/config/content/ckeditor page complaining about missing libraries, you can go to /node/add/page and see if your locally installed ckeditor is working properly. If it loads, you are good to go.

Now for the fun part, adding all those plugins that made your mouth water, but you couldn't add before you downloaded the ckeditor script library.

Go to ckeditor.com make a list of all the plugins that you desire for your local, stand alone editor, then download each plugin individually.

Extract each plugin that you downloaded to your sites/all/modules/ckeditor/plugins folder.

NOTE:  DO NOT extract the plugins folder located in the drupal sites/all/libraries/ckeditor/plugins folder... all your neat plugins and hours of work will be wiped out when you update ckeditor in the future.

After all your plugins are extracted, edit your "ckeditor.config.js" file located at sites/all/modules/ckeditor.

look for "config.extraPlugins = '';" and enter the name of your plugin.  For more than plugin, separate each plugin with a " , " .

For more details on plugin installation READ THE DOCUMENTATION HERE.

I highly recommend, adding plugins one at a time and testing in your browser, so that you can easily remove the mean plugin that won't play nice with others.

At this point go back to /admin/config/content/ckeditor and edit INPUT FORMAT that you want to use with ckeditor.  Look under "Editor Appearance" and scroll down, your added plugins should appear as checkbox options. Select the ones you want...then get back to "drupaling" :-)


Returning a custom command via AjaxResponse I have a method that is invoked by AJAX call, and it returns an AjaxResponse. It redirects the user with RedirectCommand, added to the response. However, I would like to change it to a conditional redirect. Is this possible with RedirectCommand, or any other way that uses the CommandInterface, preferably in a way that does not require implementing CommandInterface in a new class?

Indeed, one way to do this is to implement CommandInterface in a new class, as described here: https://www.mike-miles.com/blog/creating-ajax-callback-commands-drupal-8 . This method adds the new command to Druapl.AjaxCommands.

However, if it's not desirable to implement the interface, a similar thing can be done with the existing InvokeCommand that implements CommandInterface, as in the example here: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21InvokeCommand.php/class/InvokeCommand/8.2.x

My minimalistic example:

Server-side (NULL can be some CSS selector instead):

$response->addCommand(new InvokeCommand(NULL, 'customRedirect', ['/']));

Client-side:

jQuery.fn.customRedirect = function(target) {
    if (something)
        location.replace(target);
    else
        do_something_else();
};


How to re-enable content notifications for Notify? I turned off content notifications for all users for Notify some time ago because it was sending duplicates. There was a checkbox somewhere that I unchecked. It is not in notification settings.

This is Drupal 6.

Reading your comment on my question above, I guess you're using Actions & Triggers in Drupal 6.

To see which actions you have defined or to define new actions, go to Administer > Site Building > Actions. There e.g. you can define an action for sending an email. From your question I think you already have done that (in the past).

To assign this action to an event, you have to go to Administer > Site Building > Triggers. There you can choose (under Content) to assign an action to an event, such as published or updated content.


How to migrate content using a web service with multiple calls? I need to migrate content from a web service to which I have to call several URLs. A call to receive a list of nodes and then a call for each node to receive information from the fields.

Something like this:

Calling domain.test/webservice/

<results>
  <count>10</count>
  <list>
    <id>100</id>
    <id>101</id>
    <id>102</id>
    ...
  </list>
</results>

Calling domain.test/webservice/101

<results>
  <id>101</id>
  <name>Name</name>
  <field1>Field example</field1>
    ...
</results>

So, in my migration yml file I have something like:

source:
  plugin: url
  data_fetcher_plugin: http
  headers:
    Accept: application/xml
  data_parser_plugin: simple_xml
  urls: https://domain.test/webservice/

How can I specified the migrate process to retrieve each content info from a URL like https://domain.test/webservice/[ID]?

There is an issue with the UrlPerRow plugin above.

The source data isn't populated until after the check for whether the source data has changed. Because of that fact, it's always looking at previous data, which means the hash will never change, so "rowChanged()" never returns true. It will import new data but not update if the data changes.

A fixed version is below:

<?php

namespace Drupal\fad_migration\Plugin\migrate\source;

use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
use Drupal\migrate_plus\Plugin\migrate\source\Url;
use Drupal\migrate\Row;

/**
 *
 * @MigrateSource(
 *   id = "url_per_row"
 * )
 */
class UrlPerRow extends Url {

  protected $dataNewParserPlugin;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $prepare_row = parent::prepareRow($row);

    $item_info_settings = $row->getSourceProperty('item_info');
    if (!empty($item_info_settings)) {
      $this->getItemData($row, $item_info_settings);
    }

    if (!$row->getIdMap() || $row->needsUpdate() || $this->aboveHighwater($row) || $this->rowChanged($row)) {
      return $prepare_row;
    }
    else {
      return false;
    }

  }

  protected function getItemData(Row &$row, $settings) {

    $new_url = str_replace($settings['token'], $row->getSourceProperty($settings['token_replace']), $settings['url']);
    $this->getNewDataParserPlugin($new_url, $settings['item_selector'], $row->getSource());
    $this->dataNewParserPlugin->rewind();
    $xml_data = $this->dataNewParserPlugin->current();
    if (!empty($xml_data)) {
      $fields = $row->getSourceProperty('fields');
      foreach ($fields as $field) {
        if (!empty($field['item_info']) && !empty($xml_data[$field['name']])) {
          $row->setSourceProperty($field['name'], $xml_data[$field['name']]);
        }
      }
    }
  }

  protected function getNewDataParserPlugin($url, $item_selector, $settings) {
    $settings['urls']          = [$url];
    $settings['item_selector'] = $item_selector;

    $this->dataNewParserPlugin = \Drupal::service('plugin.manager.migrate_plus.data_parser')
                                        ->createInstance($settings['data_parser_plugin'], $settings);

    return $this->dataNewParserPlugin;
  }

}


How to get rid of error messages after second try where file was uploaded successfully? My question is similar to:

https://stackoverflow.com/questions/9676988/in-drupal-7-errors-for-file-managed-field-remain-even-when-fixed

Why error message from my custom file validator remains the same after next try where was file uploaded  successfully ?

How can I solve this problem?

I didn't find any JS handler which I can extend.

There is a working patch for this issue here. (File validation error message not removed after subsequent upload of valid file - 1792032)

That patch issue is waiting on someone to write tests before it can be RTBCd. It shouldn't be hard to adapt that patch to Drupal 7 in the mean time. Just make sure you document the fact that you have patched/modified core somewhere for future developers.


How to use feeds with entity reference? I have a simple example the uses an entity reference field that references taxonomy terms (e.g. "Arranger"). On import I need feeds to see if the term exists, reference it. If it doesn't exist, create and then reference it:

My CSV:

My Feed Mapping:

It imports everything else but not the entity reference field. It doesn't create the term either.

What do my feed mapping need to look like to allow entity reference to check for and if the term doesn't exist, create it (and then reference it)?

Perhaps the Feeds Tamper: String to ID module might in this situation?

A Feeds + Feeds Tamper plugin that resolves strings pulled in from feeds importers and maps them to Drupal entity IDs, so they can be used as entity references.
Adds support for freeform Entityreference linking when using Feeds.