Is Drupal 6 compatible with php5.3? We have just upgrade our server and now Our drupal 6 sites are not working properly because now the php version has been changed from 5.2 to 5.3.

is there any guide or suggestion about this? how to run a drupal6 with PHP5.3?

Thanks in advance.

Downgrading the php version from 5.3 to 5.2 solves the php problem and apparently the javascript problem as well.

System requirements says:

  Although PHP 5.3 is supported by Drupal 6.14 core and higher (see the release notes for 6.14), some contributed modules may not be compatible with PHP 5.3, and some PHP 5.3 configurations still show warnings with Drupal 6.14; work is ongoing to resolve the latter in #360605: PHP 5.3 Compatibility.

The issue linked in the requirements page is actually marked as fixed; this means that Drupal core is completely compatible with PHP 5.3 since Drupal 6.14.


Permission problems after migrating from Apache to IIS After migrating from Apache server to IIS (7.5), I have some permission problems in Drupal: modules don't seem to have the permissions to delete (unlink) or create files, not even from/into "sites/default/files" folder.

What really interesting is, that if I create my own test.php with a simple file_put_contents in it, it does create and unlink files without any error messages.

BUT for example from AddThis module I got the following error message:

  unlink(sites/default/files/addthis/addthis_widget.js) [function.unlink]: Permission denied in
  C:\<mydrupalpath>\source\includes\file.inc on line 481.

After that, I right clicked the mentioned file, Properties > Security tab > added Everyone with "Full control" rights. Not surprising, this way unlink was already successful.

BUT after that, I can see this it in the Drupal log:

  "The directory sites/default/files/addthis is not writable, because it
  does not have the correct permissions set"

OK, tried to set the right permissions with icacls with granting "modify" and "write" permission to sites/default/files directory like this:

c:\<mydrupalpath>\source\sites\default\files /t /grant "IIS APPPOOL\MyDrupalAppPool":(OI)(CI)(M,W,RX)

OK, result is "Successfully processed 228 files".
Refreshing Drupal site in browser...
Hmm, didn't work, the same error message again (permission problems)...

I don't understand... if I query the rights with icacls on "files" OR files\addthis directory, it says my application pool does have "modify" rights:

IIS APPPOOL\MyDrupalAppPool:(OI)(CI)(M)

I do have permission problems with Gallery module too... :(

What should I do not to have permission problems in "files" folder when modules try to delete from/write into it?

Thanks in advance!

From here I got the idea to run the following command on a console ("Determining the account used as IIS anonymous identity"):

%windir%\system32\inetsrv\appcmd.exe list config "MyDrupalAppPool" ^ /section:anonymousAuthentication

The result was the following:

<system.webServer>
  <security>
    <authentication>
      <anonymousAuthentication enabled="true" userName="IUSR" />
    </authentication>
  </security>
</system.webServer>

And then running the following command seems to have solved the problem of writing to/deleting from the "files" directory:

icacls c:\<mydrupalpath>\sites\default\files /t /grant IUSR:(OI)(CI)(M)

I don't know if it's secure enough... Please leave comments if you think there is any kind of problem with this approach. Thanks.


How to implement multiple approvals with emails? I am currently using the Webform module, but I can't find a way to make a workflow that works for what I am trying to do.

Please let me know if I am approaching this incorrectly, or if I should be using a different module.

This is basically how I want the steps to work:

User fills out a Webform and submits it. (one of the fields in the form is his/her supervisor's email). The form then enters a state called "Pending"
The form is sent to the entered Supervisor's email.
If the Supervisor wants to approve it, he/she will change the state to "Approved". If he/she feels that more approval from someone higher up is required, then he/she can change the state to "More Approval" needed and then enter the email of their supervisor.
If the Supervisor's Supervisor likes it, then he/she can change the state to "Approved"
When the state is at approved, HR is notified.

Is doing something like this possible? If so, how can it be done?

Instead of using the Webform module for this, I would use a custom content type for this, with the fields similar to what your webform is using. And instead of submitting a webform, a node of this custom content type is to be created.

This content type should have these fields:

A field to reflect the "state" (Pending or Approved, maybe also a state like "Escalated"?), say you name this field like field_approval_status.
An "entity reference" field to select the Supervisor.

With the above setup, you could use the Rules module to notify the Supervisor, using a rule that is similar to the rule included in my answer to "How to send an email via a Rules action using a field key?", and which looks like so:

{ "rules_notify_reviewer_about_outstanding_approval" : {
    "LABEL" : "Notify reviewer about outstanding approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--blog" : { "bundle" : "blog" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_blog_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-blog-reviewer]",
          "subject" : "Blog Post waiting your approval",
          "message" : "[node:author] has submitted a new Blog post waiting your approval.\r\n\r\nYou can review it at: [node:edit-url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

If the supervisor then wants to forward it to another supervisor, all that's needed is to edit the node and change the selected supervisor to another one.

You may want to add some extra logic and/or permissions related to such field_approval_status field, i.e. to ensure that when such node is created, the author cannot set it to "Approved" right away (only to "Pending"?). That's something you could do using the Rules module (to validate/enforce that), or you might want to use the Field Permissions module for that.

Note:

To avoid that creating nodes is too intimidating for most users, you want to look at the Simplify module also, which helps to de-clutter forms. Here is a quote from its project page:

  Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.


Associate an 'event' content type with a 'project' content type I have a project content type that can be created by users with certain permissions. I want these users to also be able to create 'events' that are associated with these project content types. So for example, A user who creates a project can create events for that project. I was thinking about putting a entityreference autocomplete field on the event content type that looked up projects created by that user (or could be people who have edit permissions on that content type). Does this  sound like a good way to do this or is there a more standard way to achieve this?

First of all i totally agree with Molot's comment.

Just to help i will provide my opinion on how to do this:

Use the Node reference url widget module in combination with the Field Permissions module. With the 1st you can create an "Add an Event" link for every Project node and set the fallback behaviour of the field as autocomplete and with the 2nd you can set the permissions for that node reference field.


Using hook_form_alter to enter placeholder in mailchimp signup fom For the signup form I'm using the Mailchimp Signup module. The idea is to hide the label, which I did using the unset(); function, and put an a placeholder in the input field where people enter their emailaddress.

Here's the code:

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

  if ($form_id == 'mailchimp_signup_subscribe_block_mysite_group_form') {
    //dpm($form);
    unset( $form['mergevars']['EMAIL']['#title']);
    $form['mergevars']['EMAIL']['#placeholder'] = t('Your emailaddress');
    dpm($form['mergevars']['EMAIL']['#placeholder']);
    }
}

dpm($form['mergevars']['EMAIL']['#placeholder']); returns the string Your emailaddress nicely in the green drupal message frame. Yet, the actual placeholder isn't there in my input element. Looking at the attributes of the particular inputfield in question, the attribute isn't added either:

<input id="edit-mergevars-email" class="form-text required" type="text" maxlength="128" size="25" value="" name="mergevars[EMAIL]">

You have to use this:

$form['mergevars']['EMAIL']['#attributes'] = array(
 'placeholder'=> t('Your placeholder'),
);


How to fix 'Cannot redeclare ctools_content_process' problem after sql-sync? I'm encountering a really weird bug with Drupal. I'm running Debian's Drupal in a multisite configuration on the same host with both the dev and live websites. I know it's not ideal but this is a constraint I cannot avoid for a variety of reasons.

So I have my sites (e.g. dev.example.com and www.example.com) and I sync them with drush sql-sync. Right after doing so, I cannot access the synced website anymore and Apache throws the following errors:

PHP Fatal error:  Cannot redeclare ctools_content_process()
(previously declared in /etc/drupal/7/sites/www.example.com/modules/ctools/includes/content.inc:18)
in /etc/drupal/7/sites/dev.example.com/modules/ctools/includes/content.inc on line 84

To make my website work again, I have to manually do a find-replace in MySQL to change any instance of dev.example.com to www.example.com in tables field_data_body and field_revision_body.

I reckon the problem is linked to CTools (and hence to views), but I have no idea why. Have any of you ever encountered such a problem?

In Drupal 7; this could be caused by corruption in the code registry. The code registry

  is an inventory of all classes and interfaces for all enabled modules
  and Drupal's core files. The registry stores the path to the file a
  given class or interface is defined in, and loads the file when
  necessary.

ref: Drupal Code Registry

The solution to this particular problem would be to force a rebuild of the registry; which you can do as per this post; Code Registry Rebuild.


How can I provide an autocomplete filter for tags in a Search API view? I'm working to create a Search API view. I have an exposed filter that's a fulltext search filter. I'd like to expose another filter that works similar to the exposed entity reference, which allows users to reference multiple tags, separated by commas; the field will then autocomplete the entered value.

Is there a way to achieve this using the Search API Views and the Search API Autocomplete modules?  As far as I can see, there isn't a way to autocomplete multiple words/phrases, instead of just the first word/phrase.

Add the datasource (entity reference) as a exposed filter.

Check the "allow multiple selections".

Now, the user can add comma seperated tags (with autocompletion):

Used search api 8.x-1.13 on drupal 8.6.16


How to implement a trial membership using Organic groups? I work on a Drupal site with the Organic groups module, where users can create account.

When the process for creating an account is finished, users have access to a specific group and should have og role Trial member (automatically assigned) with state Active, and this for a limited time period.

After that limited time period is passed, user still has og role Trial member assigned, but with state Pending.

Can someone help me with this?

Sounds like a perfect job to accomplish with the Rules module. Below are the headlines of how you could get this to work ...

Rule 1 (When user account is created)

Event: When a new user account is created
Action:

Grant access to role Trial member.
Set some Date field value = expiration date (cfr. your "limited time").
Set some State field value = Active.

Rule 2 (When expired)

Event: When user logs in
Condition: if the date indicated in field with expiration date is passed.
Action: Set your State field value = Pending.

Recommended video tutorials

Rules

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

Organic Groups

If you're not familiar (enough/yet) with Organic Groups, then reviewing the amazing set of videos to Learn Organic Groups might help.

Other variations

There are other variations to make this work with the Rules module. E.g. by using 'Rules Scheduler' (= sub-module of Rules) to schedule a variation of "Rule 2", to be executed on your expiration date.


Custom Block with form does not submit I made a custom form. After submitting you are redirected to a custom page and get a message there. So far nop.

Then I made a custom block that renderw this form into a block region. Everything appears well.

However when submitting this same form, no redirection. I am on localhost and suspect that the form is not submitting in this block. After submit I see all values in the url of my page, just like the method is GET. When I check the code the method is POST, just like the original form, also Drupal added some classes which are the same as in the form.

I discover that the reason is because of the localhost. Once life the form is submitting by the FormSubmit handler.


Checked as default --> The user must confirm the account cancellation via e-mail. How can I checked as default the value Require e-mail confirmation to cancel account.
It is unchecked as default :(

I tried to edit user.module editing this line '#default_value' => TRUE, but it doesn't work

  // Allow to send the account cancellation confirmation mail.
  $form['user_cancel_confirm'] = array(
    '#type' => 'checkbox',
    '#title' => t('Require e-mail confirmation to cancel account.'),
    '#default_value' => TRUE,
    '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'),

Consider never modifying core or contrib modules.

Instead, the right practice here is to use hook_form_alter() or hook_form_FORM_ID_alter() in a custom module.

So, configure a little module and put the following code in it:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  //get your form id
  drupal_set_message("Form ID is : " . $form_id);
  switch($form_id) {
    case 'MY FORM ID':
      $form['user_cancel_confirm']['#default_value'] = 1;
      break;
    case 'OTHER FORM ID':
      //do sthing
      break;
    //...
  }
}


How to change a user to a different role based on the number of their posts? Are there any techniques out there that can put a user in a specific role into a different role automatically after they make X number of posts (core forum topics or/and replies)?

I'd like to implement a functionality where when users first register to my site they get put into a role which has limited privileges, but after certain number of posts to the forum (new topic or replies to existing) they get put into a different role that doesn't require CAPTCHA and they can post links etc. FYI using the core Forum and the Advanced Forum module.

I found a module User Stats which integrates with Rules and provides tokens like [user:post-count] which can be used for numerical comparison. Hope this helps someone else.


How do I log in a user? I want to log in Drupal 8 users from an external PHP file. I am trying the following code.
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\user\UserInterface;
//$autoloader = include('/vendor/autoload.php');
$autoloader = require_once __DIR__ . '/vendor/autoload.php';
$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

// ID of the user.
// REPLACE WITH WHATEVER ID YOU WANT TO LOGIN AS;
$uid = 100;
$user = Drupal\user\Entity\User::load($uid);

// This is required to call user_login_finalize here.
$kernel->prepareLegacyRequest($request);
user_login_finalize($user);

$response->send();

$kernel->terminate($request, $response);

When I run it, I get the following error.

TypeError: Argument 1 passed to user_login_finalize() must implement interface Drupal\user\UserInterface, null given, called in /var/www/html/stocksee/public_html/component/login.php on line 22 in user_login_finalize() (line 554 of core/modules/user/user.module).

Please help me.

I'd say in this specific case the error message looks like saying that $user is NULL. You need to validate that User::load returns a valid UserInterface because if the $uid passed to the method is not found, it will return NULL, which is the value you are getting. Try with a valid uid like 1, see what happens and move ahead from there.


Programatically Submitted Form With 'file' Field Throws Notice This seems to actually be a problem in Drupal itself. In /modules/file/file.field.inc the function file_field_widget_form has a line like this near the bottom (just before the return statement):

$elements['#file_upload_description'] = theme('file_upload_help', array('description' => '', 'upload_validators' => $elements[0]['#upload_validators']));

The issue is a small if condition a few lines back which looks like this:

if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {
    $elements[$delta] = $element;
    ...
    some more stuff
}

Since I am submitting my form programatically with drupal_form_submit, it adds in $form_state['programmed'], thus the if condition fails, $elements[0] does not exist and I get the error

Notice: Undefined offset: 0 in file_field_widget_form()

My form is submitted by a custom routine (in a custom module) that looks a bit like this:

foreach ($field_data as $k => $detail) {
    $field_key = _get_field_keys('field_' . $k);
    $field_key = $field_key[0];

    $node -> {'field_' . $k}[$node -> language][0][$field_key] = $detail;
    $form_state['values']['field_' . $k] = $detail;
}

drupal_form_submit("{$node->type}_node_form", $form_state, $node);

The form state before I call drupal_form_submit looks like this:

Array
(
    [values] => Array
        (
            [title] => some title
            [name] => admin
            [op] => Save
            [field_person] => 88
            [field_lead_type] => 1
            [field_lead_details] => some stuff
    )

)

What is the fix? I'd rather not mess with core modules. Is there something I can do to my own code to resolve the problem?

ok, why are you not submitting a File (or FID) along with your form_state? I don't understand your problem, because I do this all the time (even with files).

Drupals file widgets usually use like Ajax to upload a file in the background and the form takes a FID in $form_state to process your forms if it has files attached.

When I asked you what the $form_state was I meant:

what are you sending to drupal.
what does drupal typically send as the $form_state when that form is sent through the user interface, because you're just trying to do that programmatically.

I dont think you know the answer to (2) above, because you cant get this to work right. You showed me what you're sending for (1). Here is a tutorial on using Firefox's Firebug plugin to view the submitted POST form state values for a drupal form. You want to drupal_form_submit form state to have the exact same parameters passed to it. In firebug you simply press Persist in the Net tab and you can capture URL requests.

So I'm saying goto the form in the website and submit it using your browser and Firebug to see what it expects to be passed.

You may ask how you get a FID for a file, you simply upload it using php before submitting the form and pass along its $file->fid. See this community documentation comment here how to do that.

You're just posting a simple HTTP Form, I really doubt Drupal is doing anything wrong.


In a custom module how do I get all the nodes of a certain type? Do I just do a direct db_query() on node/node_revision, or is there a function?

You use db_query() to get the node IDs for all the nodes of a content type, and then node_load() to load the single nodes one by one.

$query = db_query("SELECT nid FROM {node} WHERE type = '%s'", $type);

while ($result = db_fetch_object($query)) {
  $node = node_load($result->nid);
  // Use $node or store it in an array;
}

As the query is fetching a single field, db_fetch_object() could probably be replaced with db_result(); I have never checked if it works for all the database engines, and I didn't find a Drupal core module that uses db_result() in a loop (e.g., while ($nid = db_result($query))).

The reason you should use node_load() is that:

It allows the module that define the content type for the loaded node, and third-party modules to add extra fields in the node object. This is because the function uses the following code:

// Call the node specific callback (if any) and piggy-back the
// results to the node or overwrite some values.
if ($extra = node_invoke($node, 'load')) {
  foreach ($extra as $key => $value) {
    $node->$key = $value;
  }
}

if ($extra = node_invoke_nodeapi($node, 'load')) {
  foreach ($extra as $key => $value) {
    $node->$key = $value;
  }
}

It loads the correct node revision, when revisions are enabled for the content type.
It caches the result; if two calls to the functions are requiring the same node, the function simply return the previous result. This happens if the call to the function doesn't require a specific revision of the module, and if the last parameter passed to the function ($reset) is not equal to TRUE.

If you are interested to get only the node ID, then the call to db_query() is sufficient.

In Drupal 7, there is a class that allows to load multiple entities (Drupal 7 nodes are entities) that match some criteria in once: EntityFieldQuery.


Login Users action in, $action_links, how do i edit it? I am still very new to drupal and have let to use all the hooks and coding needed to do everything, now I have come up with a problem, which I can not seem to fix either with a module or by looking at code posted online.

I am using the forum core module from drupal 7 to build a forum, within my page.tpl file I have the render($action_links) option printed on each page. This works fine for logged in user. It displays a 'add new forum topic' as a link. However when a non-user views the forums, its displays 'Log in to post new content in the forum'.

My problem / issue is that only the 'Log in' words are linked to the user login in page and not the whole text. I would like to move the  tag drupal placed after the 'Log in' and move it to the end of the text!

I think I would have to use hook_menu something but I can't really find any information on how to do this for the $action_links. All the hook_menu options I find seem to deal with controlling the main menu output.

Any help give would be most welcome...

Thanks

Glenn Curtis

In D7, if you visit core FORUM module & open forum.module file you will find this code between line no 186 to 208 -

if (empty($links)) {
        // Authenticated user does not have access to create new topics.
        if ($user->uid) {
          $links['disallowed'] = array(
            '#theme' => 'menu_local_action',
            '#link' => array(
              'title' => t('You are not allowed to post new content in the forum.'),
            ),
          );
        }
        // Anonymous user does not have access to create new topics.
        else {
          $links['login'] = array(
            '#theme' => 'menu_local_action',
            '#link' => array(
              'title' => t('Log in to post new content in the forum.', array(
                '@login' => url('user/login', array('query' => drupal_get_destination())),
              )),
              'localized_options' => array('html' => TRUE),
            ),
          );
        }
      }

This is responsible to generate the link & text which you are talking about. But hacking core is not advisable so please find a way to do it in some other way..


Dynamic and/or flexible content types First of all, apologies if this has already been covered, but since I have no idea of what I'm looking for, it's a bit hard to find information about my problem.

Then, the problem: I'm looking for a way to create pages with any number of any type of (pre-existing) fields. For example, I may want a plain old page with its body text and that's it. Then some day I might want a page with body text and a picture gallery, and that's also easy. Then I might wake up one morning and want to have a page with a gallery to begin with, then some text, then another gallery, then a list of mp3 files. And then whatever I need on a daily basis.

Now, as this is for my personal web site, I could easily get my hands dirty with HTML and be done with that, but suppose one day one crazy client of mine comes up with a similar request. What am I supposed to do? Surrender to the evil "15yo nephew" that "can do it no sweat in a matter of hours and a fraction of your paycheck"? See, I use my web site as sandbox/gym to prevent situations like these :)

Any suggestion is welcome (although I'd rather keep Panels as a last resort, and I'm not even sure it does what I'm asking).

EDIT Here's a good example of what I'm trying to achieve, except that that site is uses Wordpress so I'm guessing everything has to be done by hand

A CMS like Drupal is a way to create structured content types to make it easier to author large numbers of pages with the same structure. This is actually great from a user experience perspective, as the user expects information to be presented to her in a consistent manner from one page to the next.

The user will be fine with multiple presentation types if the information architecture is consistent, but if your structure is all over the map, the user will quickly tire of having to figure things out.

So for the majority of your site, plain old content types will probably serve you best.

If you are talking about overview pages, then getting used to Panels will probably make it something other than a 'last resort'. It is quite powerful, and customizable. The alternative, if you wanted daily customization, would be to create a single content type, and add and remove fields at will. However, I believe that after a while you are going to wish you had selected to use panels. Eventually you are going to want to re-use something you had before.

When you are using a CMS, think in terms of building blocks, and how to combine them to reach your goals.


EntityMetadataWrapperException when accessing empty entity body. How can I test if body is empty first? The following call

$body = $entity->body->value->value();

throw the following error

EntityMetadataWrapperException : Unable to get the data property value as the parent data structure is not set. dans EntityStructureWrapper->getPropertyValue()

when the body is empty.

How can I prevent it?

Just simply see the value is empty

if($node_wrapper->body->value() != ""){
 //Evaluates true
}

or use a try catch

try{
 echo $entity->body->value->value();
}catch(Exception $e){
  echo "Value does not exist continue";
}


Drupal 8 Ajax Form Submit works only once? I am trying to create a simple form in D8 that submits with a submit button and then replaces the entire form content via ajax.

For some reason, my AJAX submit works perfectly on the first click but then kicks in a normal submit handler.

This Works

  public function getFormId() {
    return 'my_form';
  }

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

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit ').time(),
    '#ajax' => [
      'callback' => [$this, 'loadStep'],
      'wrapper' => 'form-test',
      'effect' => 'fade',
    ],
  );

return $form;
}

public function loadStep(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$form['submit']['#value'] = time();

$response->addCommand(new HtmlCommand('#form-test', $form));
return $response;

}

public function validateForm(array &$form, FormStateInterface $form_state) {

}

public function submitForm(array &$form, FormStateInterface $form_state) {
// TODO: Implement submitForm() method.
}

This Does NOT work

  public function getFormId() {
return 'my_form';
}

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit ').time(),
    '#ajax' => [
      'callback' => [$this, 'loadStep'],
      'wrapper' => 'form-test',
      'effect' => 'fade',
    ],
  );

return $form;
}

public function loadStep(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$form['#prefix'] = '
';
$form['#suffix'] = '
';
$form['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#required' => TRUE,
);
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit ').time(),
  '#ajax' => [
    'callback' => [$this, 'loadStep'],
    'wrapper' => 'form-test',
    'effect' => 'fade',
  ],
);
$response->addCommand(new HtmlCommand('#form-test', $form));
return $response;

}

public function validateForm(array &$form, FormStateInterface $form_state) {

}

public function submitForm(array &$form, FormStateInterface $form_state) {
// TODO: Implement submitForm() method.
}

It seem like as soon as I add something more substantially than just changing the label on the submit button, it seems to fail from the second submit where it just invokes a regular submit.

I want to replace the entire form on every submit (basically creating a multistep form).

I am running 8.3.2 btw

Many thanks for all help.

Your problem is probably here:

$form['submit']['#value'] = time();

You are changing the value of the submit button in the ajax callback. However, Drupal has already cached the form before the Ajax callback is hit. Why that matters is that Drupal uses the value of the submit button to determine which button was clicked, comparing it to the values in the cache. Since your cached value will be different than the submitted value, it cannot properly determine what it needs to do.

You need to change the value of the submit button either in the form definition, or in a form_alter hook.


Updating Node Field using drupal_write_record doesn't show changes until cache flush Problem is in the title basically, I'm trying to update a specific field in my node and I have to do it by using drupal_write_record rather than loading and modifying the node object itself, or by using node_save etc, but my changes aren't being reflected until I flush the caches for the site.

Is there something I need to do to have Drupal immediately aware of the changes?

Code:

$next_delta = db_query('SELECT MAX(delta) + 1 AS del FROM {field_data_my_field} WHERE entity_id = :nid', array(':nid' => $nid))->fetchField();
  $data = array(
    'entity_type' => 'node',
    'bundle' => $node->type,
    'deleted' => 0,
    'entity_id' => $node->nid,
    'revision_id' => $node->vid,
    'language' => LANGUAGE_NONE,
    'delta' => $next_delta,
    'field_my_data' => 1,
  );
  drupal_write_record('field_data_my_field', $data);
  drupal_write_record('field_revision_my_data', $data);

I've tried adding entity_get_controller('node')->resetCache(array($node->nid)); into the code but that's not doing it either.

When you write directly to the table (which drupal_write_record() does), it bypasses any APIs that are called. As such, you should really only use drupal_write_record() for tables you've created yourself, that don't have any APIs to be bypassed.
In this case, you are better off changing the values in the $node, then calling node_save() on it. This will not bypass any APIs.


Cannot make query substitutions I am using Drupal 7 and Views 7.x-3.7 . I am trying to display posts on my site using a SQL query that looks like this:

SELECT DISTINCT node.title AS node_title, node.nid AS nid, node.language AS node_language

FROM

{node} node

ORDER BY node_title ASC

The problem with this query is that if I have multiple posts with the same title,then all are being displayed because the nid, which is the primary key, was added by Drupal. I have been trying to remove the nid by using the hook_views_query_substitutions() method, but I have had no success. The method is getting called, but my query is not being updated.

I call zz_views_api() from my zz.module, and have the following zz.views.inc

function zz_views_query_substitutions($view) {
  // description of  zz_views_query_substitutions().

  return array(
    'node.nid AS nid,' => ' ',
  );
}

I think this is a similar situation to a question I asked a little while ago.

I solved it by using hook_views_query_alter() to remove the fields I didn't need in the query.   In your case, it would probably look like:

function MYMOODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'MY_VIEW') {
    unset($query->fields['nid']);
  }
}

dpm() the $query to see what array keys are in $query->fields if that doesn't work.


Alternative for hook_node_submit() What is an alternative to hook_node_submit() for Drupal 8?

This is what the related change record has to say:

  Instead of the submit hook, an #entity_builder callback should be used to map form values to an entity (or better; use a field with a widget). If the submit hook is not about mapping values to the entity, register a custom #submit callback on the submit button and put your logic there.

And here are the related code samples:

// Implements HOOK_form_BASE_FORM_ID_alter
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  // For entity builders.
  $form['#entity_builders'][] = 'mymodule_node_builder';
  // For submit callbacks.
  $form['actions']['submit']['#submit'][] = 'mymodule_node_form_submit';
}

function mymodule_node_builder($entity_type, NodeInterface $node, &$form, FormStateInterface $form_state) {
  $parent = $form_state->getValue('menu', 'parent');
  if ($parent) {
    list($node->menu['menu_name'], $node->menu['plid']) = explode(':', $parent);
  }
}

function mymodule_node_form_submit($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  mymodule_do_something($node);
}


Acsessing field data for a views template I have a client who wants to be able to input a content type which allows for the upload of 4 different pdf files. They want to have a view that allows them to click on one link and load each pdf file in a separate tab. I can get this to work in the footer of the view with the global text option and inputting the following code:

[title]

The problem is, I need this to work in the fields using the global text option but full html is not allowed there. I am trying to use a views template file to input the code but I can not figure out how to access the data that is supplied by the replacement patterns in the view. Any tips on how I can assign variables with the right data in the template file?

Use the Theme: Information in the Advanced part of the view configuration (you need to click the Advanced link to expand it).

Here you can explore all the possible templates for that specific view and specific display. But additionally you can click the specific template and see the default code (in your case you will use Row template I guess). There you can see the available variables.

To print out the specific values, I would recommend Devel module and then the kpr() or dpm() functions, like this: dpm($fields); in your template.

Alternatively, you can use debug($fields); without using the Devel module.

Important: Do not forget to delete these debug functions before deployment.


How to use taxonomy terms(with depth) on a views exposed filter? I have a taxonomy vocabulary with 'Countries' as parents and 'Cities' as children.
I want to expose the terms with two views exposed filters,one for the parents and one for the children.But both filters show all parents and children terms.
How can I accomplish that,to show only parents term to one filter and children terms to the other filter?
Thanks in advance

http://drupal.org/sandbox/ser_house/1832320 is not done but i am using it on my site and works fine even with other exposed filters.

Only problem not really related to this module is that my vocabulary is 5000+ terms and its Drupal taxnonomy core issue on how to handle large amount of terms.


Configuring Drupal for Upstream Deployment I'm trying to help a co-worker configure a Drupal site so that we can deploy the same site upstream without making database changes. We're having trouble with file paths. Here's what I have:

A Nginx webroot pointing to the root of my Drupal 7 (in this case) install (/opt/frameworks/drupal-7).
The content for this site is in /opt/www/my-site.
A symlink exists in /opt/frameworks/drupal-7/sites: dev-my-site -> /opt/www/dev-my-site

Because of some sharing that's going on, there are multiple versions of my-site on the box, so they have to have different symlink names. Right now, the "file system path" is set to sites/dev-my-site/files which breaks when moved upstream.

We're both inexperienced with Drupal and trying to help out a client. Upstream we get this:

Fatal error: require_once() [function.require]: Failed opening required '/opt/frameworks/drupal-7.15/sites/www.productionurl.com/modules/entity/includes/entity.inc' (include_path='.:/usr/share/php:/usr/share/pear') in /opt/frameworks/drupal-7.15/includes/bootstrap.inc on line 3084

At each point in the deployment process (dev, staging, production), the path will be slightly different. For example, .../sites/dev.myclient.com/modules/..., .../sites/stg.myclient.com/modules/... and .../sites/myclient.com/modules/.... When I deploy, what do I need to change to ensure that this works?

In Drupal 6, I was able to set the file_directory_path variable in settings.php, but that doesn't seem to be an option in Drupal 7. What's the alternative? Is there one?

This might be just a shorthand difference, but the include is looking for /drupal-7.15/ but you mention /drupal-7/ earlier in the post. Do you have two different versions of Drupal installed somehow, or is this all deployed from the same duplicate codebase and you're just trying to switch directories depending on the env?


A nice way to build a related content algorithm I am making a custom D7 module which has a block that lists related nodes of the current node you're viewing. The relation is determined by Taxonomy terms (from 1 vocab). The complication is that the related nodes need to be ordered by how many tags are matched in descending order.
How can you order nodes by matching tags? I have an idea of how to select nodes with matching tags, but have no clue as to how to order these by the number of matching tags. Any suggestions? Do it in SQL or in PHP?
Are there any modules that implement such functionality?
Simple case study for clarity
I have 2 content types: basic_page, article
Both of these content types have a same term reference field: field_tags
When someone opens a basic_page node that has been tagged with Tag A, Tag B and Tag C, I want to show article nodes that have been tagged with Tag A, Tag B and Tag C. But these article nodes need to be ordered by 'relevancy'. For example: the article nodes with all 3 tags matched must be at the top, and article nodes with 2 matching tags comes next, then the ones with 1 matching tag.

This was what I ended up writing to select nodes:

$query = db_select('node', 'n');
$query->addField('n', 'nid');
$query->addExpression('COUNT(n.nid)', 'ncount');
$query->innerJoin('taxonomy_index', 'ti', 'n.nid = ti.nid');
$query->condition('ti.tid', $tids, 'IN');
$query->condition('n.type', $types, 'IN');
$query->condition('n.nid', $node->nid, '<>'); // Exclude current node
$query->condition('n.status', 1); // Published
$query->condition(
  db_or()->condition('n.language', 'und')
         ->condition('n.language', $node->language)
);
$query->groupBy('n.nid');
$query->groupBy('n.title');
$query->groupBy('n.created');
$query->orderBy('ncount', 'DESC');
$query->range(0, 10);

$results = $query->execute();

Kudos to Similar by Terms module, as I copied most of it from there. The magic happens when you order by ncount field.


Large ecommerce sites that are built on drupal I'm having trouble trying to convince the team to adopt Drupal commerce/Ubercart.
Would anyone know of some large websites that are built on Drupal?

Drupal Commerce sites:

http://www.eurocentres.com/en
http://www.commerceguys.com/customers/showcase

Ubercart  sites:

http://www.topsite.com/best/ubercart

High profile sites:

http://www.infomagnet.com/content/high-profile-high-traffic-drupal-websites

Government sites:

http://govfresh.com/2010/02/5-government-sites-using-drupal-effectively-for-open-government-initiatives/


Why field is double when I print it in node.tpl.php I have a issue. I created a field in "content types > article". Then I went to node.tpl.php and added next code:

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

after that, I cleared cache and saw double field in my article.
I tried to hide this field in "manage display" but it didn't successful, my field disappeared at all.

I just want to render my field in a certain place in the node.tpl.php

Try wrapping the field in the hide function.

hide($content['field_like']);

Do this after you have output your field but before you call render($content).

see https://api.drupal.org/api/drupal/includes%21common.inc/function/hide/7.x


How to get a notification when user is blocked following flood I'm trying to get an email sent to me every time an account is banned following a flood (5 tries).

Unfortunately, a user that is blocked isn't set to "status = 0", so I cannot use a rule based on user status. I did a few search and couldn't find Rules integration with the Flood Module.

Is it part of the core? Is there anything other way to provide Rules integration with Flood?

Yes, Flood is part of core (it lives in includes/common.inc, and because Rules is a contrib module, there is no set way to integrate cleanly in Drupal 7.

The one thing you might be able to do is to do a form_alter() on functions like user_login_final_validate($form, &$form_state), since if a flood event has been triggered they will include a form value such as $form_state['flood_control_triggered'] which, when it is not empty, will indicate that a login attempt has been blocked. Then of course your custom form_alter implementation can call any Rules events it likes.

This is totally untested so I can't verify that it would work, but for now there doesn't seem to be an easy or clean way to do this in D7.


302 Redirect with cron.php On a rather old drupal site (D5) I get a 302 on calling cron.php when doing this via wget or curl. It worked fine for many years (via crontab). If I use a browser for that I get a 200 and a blank page (which is normal) the cron runner runs successfully. After trying to find a solution for a couple of hours it works fine with curl for no apparent reason, but not with wget and only if I run it directly (still 302 with crontab). As I type this I try again just to make sure and now neither wget nor curl work anymore, but running it through the browser still works just fine. Strange.

curl: curl -s http://www.mysite.com/cron.php
wget: wget -O - -q -t 1 http://www.mysite.com/cron.php

Any ideas?

302 redirect can happen due to Either server settings or manual redirect inside modules using functions like drupal_goto....

You need to debug to understand the problem.. Here are the steps to find out where it is going wrong...

To make sure it's not related to server settings go and comment below line in drupal_cron_run function inside includes/common.inc...

// module_invoke_all('cron')

If you cannot able to replicate 302 error then it's for sure some module which is implementing hook_cron is doing above redirect other wise check your .htaccess or server settings to debug more..
If you don't see 302 error go and uncomment above code you have commented to debug further...
Run below code in any page to understand which are modules implementing hook_cron.....

Code:

foreach (module_implements('cron') as $module) {
  drupal_set_message($module);
}

Verify all above modules which implements hook_cron doesn't have any redirect code.. Check custom modules in particular...
If nothing works.. Use Debugger like XDebug to debug step by step.


Advice on latest drupal security advisory having followed most of the instructions do I rebuild the server? I was unfortunately on holiday on the week of drupageddon / drupalgeddon / security advisory SA-CORE-2014-005. So my site was a week without having core updated/ patch applied at all. I started off reading through this post and, apart from the Hacked module which I couldn't understand and therefore didn't try, nothing seemed to have happened. Nothing seems to be a breach, but as I read - that's the point... So generally speaking I'm preparing to rebuild the server, but in all this it will take ages as I'll have to check through all the user submitted data. How is the hack able to lead to everything possibly being vulnerable? Looking through the permissions the only things that are owned by "apache" are the "sites/default/files" files. Do I need to rebuild the server?

I updated core immediately, then used the Drupalgeddon module which found nothing (and again found nothing just now):

"Site did not test positive. Good luck!                               [ok]"

I checked through the live source against our development repository and I couldn't see anything obvious that was suspicous.

I used Toad for MySQL to do a comparison of my live db with a dump of the database before the 15th of October and that did not show anything that I thought might be a problem. I kept doing what I was shown (!) in terms of permissions:

Group: root[0]; Owner: root[0]; Octal: "0755" for

/sites/all/modules
/sites/all/themes
/sites/all/libraries

Group: root[0]; Owner: root[0]; Octal: "0444" for

settings.php

Group: root[0]; Owner: root[0]; Octal: "0644" for

all root of web directory stuff like...
/install.php
/index.php
the files within the other folders off the root of the web directory

The folders:

/themes
/scripts
/includes
etc.

have Group: root[0]; Owner: root[0]; Permissions: Octal:"0755"

Which I thought (and which is why I deliberately kept it like that) made everything quite locked down in terms of file access and permissions etc.

So after all this I was struck with a similar scepticism as this article on ZDNET.

Any suggestions? Do those permissions/ ownership help to protect? Do I really need to rebuid? The latest claims are if you didn't update within 7 hours, you've been hacked. The sites are actually fairly new and atm get roughly 5000 sessions a month. Also, coincedentally, I removed user/register to prevent spam because our setup uses a bespoke arrangement for registration.

You have a couple of questions here so I'll answer the one that I can. File permissions.

The short answer is it depends on your setup as to what the best permissions are.

It depends on your system's users and groups and what account runs the web server process.

There is a lot of more detailed information at Securing file permissions and ownership.

I will give one specific though:

Something to consider aside from the security of your website is the security of your server.

If all your files have to be edited by root does that possibly mean you are regularly using the root account or sudo to do things?
If so that is bad for server security. You shouldn't really need to be root to edit website files like that.

Instead of using root maybe use a non-root account with a strong password.

Remember, root is no stronger than any other user in terms of what password they are required to log in with, but has infinitely more power once they're in.


Field Collection : Query to get the node id by sending a value of a field collection field value I am having a field collection in a content type called 'client'.
There are,

Client name
Email
Mobile
Address 1
Address 2
Address 3
etc..
as fields. That's it in the client content type.

I am having another content type which basically has a textfield and a dropdown list
The texfield allows to enter a client's name
Once the client's name is filled in the textfield the dropdown list should be filled with  client's addresses
So what I am trying to do here is, programmatically generate the dropdown options by sending the client's name and getting their relevant addresses which was saved using the client content type.
I'm quite confused with DB structure for field collection values.

Would be great if you can help ASAP

Thank you.

You could try Field Collection Values

As it says, try

  To get the values of the individual field items call the entity_load
  function:

<?php
  $node25 = node_load(25);
  $track_1 = entity_load('field_collection_item', array($node25->field_track[LANGUAGE_NONE][0]['value']));
  $track_2 = entity_load('field_collection_item', array($node25->field_track[LANGUAGE_NONE][1]['value']));
?>


How to display a form in modal dialog on page load? This is on Drupal 8.6, PHP 7.2, Theme is based on Bootstrap.

The scenario is, I want to display a dialog box with a subscription form in the home page. The dialog box will be loaded automatically when page load, not by click any link.
I see there are lot of examples there in the net, but all related to by clicking a link, modal will display. But I want to load it without any click.

I partially successful by using BootstrapDialog, but ajax is not working on form submit button. What I did, I attach a js file in the front page, with the code below. It shows the Modal Dialog box, and I tuned a page--newsletter--subscribe.html.twig, its working But submit button not working not ajax is working.

    BootstrapDialog.show({
    title: 'Subscribe To Newsletter',
    message: jQuery('

').load('/newsletter/subscribe'),
    closable: false,
    draggable: true,
    closeByBackdrop: false,
    closeByKeyboard: false,
    buttons: [{
        label: 'Close',
        action: function(dialogRef){
            dialogRef.close();
        }
    }]
});

I saw there is an example in code node.preview.js file like this:

          var $previewDialog = $('
' + Drupal.theme('nodePreviewModal') + '
').appendTo('body');
      Drupal.dialog($previewDialog, {
        title: Drupal.t('Leave preview?'),
        buttons: [{
          text: Drupal.t('Cancel'),
          click: function click() {
            $(this).dialog('close');
          }
        }, {
          text: Drupal.t('Leave preview'),
          click: function click() {
            window.top.location.href = event.target.href;
          }
        }]
      }).showModal();

But I never able to make it working in my custom module.

If some one can help on this, will be really great!

Update:
I just tried to put a link manually in the template and tried to open the dialog, but it gives me some error:

Show Dialog

The error is as follows:

dialog.js?v=8.6.4:35 Uncaught TypeError: $element.dialog is not a function
at openDialog (dialog.js?v=8.6.4:35)
at Object.dialog.showModal (dialog.js?v=8.6.4:52)
at Drupal.AjaxCommands.openDialog (dialog.ajax.js?v=8.6.4:96)
at Drupal.Ajax.success (ajax.js?pkvhqx:155)
at Object.success (ajax.js?v=8.6.4:234)
at i (jquery.min.js?v=3.2.1:2)
at Object.fireWith [as resolveWith] (jquery.min.js?v=3.2.1:2)
at A (jquery.min.js?v=3.2.1:4)
at XMLHttpRequest.<anonymous> (jquery.min.js?v=3.2.1:4)

It seems some of the library is not loaded. Here is my global attachement:

  dependencies:
- core/jquery
- core/jquery.ui
- core/drupal.ajax
- core/drupal
- core/drupalSettings
- core/drupal.dialog
- core/drupal.dialog.ajax
- core/jquery.form
- core/jquery.once
- core/modernizr

What I did, hide the link in the body and from javascript trigger the click event of the link, will show the dialog.


Frustrating Drupal perfomance i've started using Drupal few days ago and from the start i've noticed very slow page load, right after installation, i though it's normal and forgot for a while about this problem.
I am running Apache 2.2 and PHP 5.3 on local PC (Core2Duo 2.4, 3GB Ram)
with Drupal 7.14. I have tried using shared hosting (5% of some Xeon CPU, 256Mb Ram for PHP) - same problem, pages took ages to load, not to mention Admin pages loading for 3-5sec, sometimes - minutes. Sometimes UI and Pages are very good, sometimes it hangs for few seconds, minutes even. Always using Ctrl+R for page reload to skip caching on browser side.
Today I've installed Performance module and did the test on shared host with a little content on page and on blank installation of Drupal at local machine mentioned above.
Results on Local: http://s14.postimage.org/ij1isbh33/Drupal_7_Local_default.jpg
Results on Shared: http://s11.postimage.org/asjhasu29/Drupal_7_shared_content.jpg
On local - first time its default installation, second time logging disabled, caching everything, aggregation etc.
Therese a phpBB3 default running on shared and local - very responsive, no hangs, page loads in a few ms.
Also, the amount of Queries, is this normal for Drupal to have 30-200 Queries?
What could be the problem with this issue?

Things to try:
http://groups.drupal.org/node/242443
http://groups.drupal.org/node/210683

But in reality we don't know until you can profile the code.
http://getmuhammad.blogspot.com/2011/08/installing-xdebug-and-webgrind-on.html


Implementations suggestions for content on front page My front page needs to look like the following:

The header, navigation, and white content areas are part of my page.tpl.php, and show up on all pages.

I'm assuming I can power the blue Image Carousel by creating a content type that contains an image and caption, then create a view that pulls those images out of the database.

Below that are 3 areas which contain different stuff.

"1" is an image that is a link. The image and link need to be controllable by the admin.
"2" is a Facebook social plugin. I'm assuming I can just create a content block and paste the HTML from Facebook into that and assign that block to show up on the front page, somehow.
"3" is another, smaller, image carousel, but will most likely use a different content type (assuming I should be using content types for this at all).

What is the best way to put this page together?
It doesn't need to be completely flexible from the admin screens. I'm OK with building a front page template.

How would you build this page? I'm getting to the point where I can get things to work, but I don't think I'm doing them in the most efficient and/or Drupalish way.

I'd use Panels to handle the layout.  Panels will allow you to create a customized front page without using any templates from within the Panels interface.  I can't describe in detail how to use Panels here but Node One has an excellent series of screencasts on Page Manager and Panels.

Using Panels will allow you to easily give the front page a unique look which you can change at any time by simply logging in to the site (as an admin) and opening up the Panels interface.

For the slideshow, try the Views Slideshow module.  It is well-documented (links on the module page) so you shouldn't have too hard of a time setting it up, and it is widely used (more than 100,000 sites).


Alter a path alias depending on a node property I use the Pathauto module and I'm trying to get, for the same content type, two different path aliases depending on a Boolean field that content type has.

I would like to have a path alias like mysite/node_name if the Boolean field value is false and  mysite/[a generic term]/node_name if its value is true.

Is there a way to do this?

if you don't won’t to create a new token as @Clive mentioned in comment, you can use hook_pathauto_alias_alter in your custom module like the following.

/**
 * Implements hook_pathauto_alias_alter().
 */
function MY_MODULE_pathauto_alias_alter(&$alias, array &$context) {
  if ($context['module'] === 'node' && $context['bundle'] === 'MY_BUNDLE') {
    // Get the node.
    $node = $context['data']['node'];

    // Clean string service.
    $clean_string_service = \Drupal::service('pathauto.alias_cleaner');

    $is_checked = $node->field_SOME_NAME->value;
    //   If your field is checked.
    if ($is_checked === 1) {
      $alias = '/mysite/term/' . $clean_string_service->cleanString($node->label());
    }
    else {
      $alias = '/mysite/' . $clean_string_service->cleanString($node->label());
    }
  }
}


D8 - How to modify url params on form submit? Im using form_alter on a views exposed filter form. There are 2 date fields (start-date and end-date) which are exposed filters that Ive hidden from the user. I want to populate the url argument of these 2 fields when the form is submitted.

Ive tried both methods using a submit and validation callback but neither seems to work.

My form_alter is:

function mymodule_form_views_exposed_form_alter(&$form,
  FormStateInterface $form_state, $form_id) {
    if ($form['#id'] == 'views-exposed-form-my-form-id') {
  ...
  ...

  $form['#submit'][] = '_my_custom_submit';
  $form['#validate'][] = '_my_custom_validate';
}

My callback looks like:

function _my_custom_validate($form, FormStateInterface $form_state) {

  // Pass date range selection to date fields.
  $date_range = $form_state->getValue('date-range');
  $date_range_split = explode(":", $date_range, 2);
  $start_date = $date_range_split[0];
  $end_date = $date_range_split[1];

  $form_state->setValue('start-date', $start_date);
  $form_state->setValue('end-date', $end_date);

  $input = &$form_state->getUserInput();
  $input['start-date'] = $start_date;
  $input['end-date'] = $start_date;
  $form_state->setUserInput($input);
}

When I dpm() any of my vars above I see the data but I can not get it passed into the url's arg on submit so I keep getting http://domain.com&start-date=&end-date=

How can I populate/modify the url args after the user clicks submit but before the page reloads?

If theres any other info that I can provide that may be helpful, please let me know.

Thanks!

You might have a logic-error in

$input['end-date'] = $start_date;

should be this:?

$input['end-date'] = $end_date;

How ever you can add a parameter with "query->add":

\Drupal::request()->query->add(['start-date' => $start_date, 'end-date' => $end_date]);

Note that you "mix" POST and GET - variable. So in your "submitForm" - method you need to process the GET - variables by yourself.


What items in the DB do I need to edit when switching from a multisite to a single site? I've copied a single site from a live multisite setup to my local (MAMP) server. The content is showing from the site however it is unstyled (and also the home page is showing the 404 page). I assume there's some changes I need to make to the DB to fix this and allow the site to function correctly.

I'm running version 6.22

Since your content is showing, your DB connection is OK.

Even if you don't have DB access to the multisite, you should have DB access to your local (MAMP) server.  And even if that site's styling is broken, you should still be able to back up its contents using Backup and Migrate.

The fact that the content is unstyled and 404 shows on the home page indicates that your basic site setup is not correct.  IIRC, Drupal 6 did indeed appear unstyled if you migrated content between sites without resetting to the default (Garland) before migrating.

There may be a more direct way to repair this (I think  Mołot's link in his first comment points to such a recipe), but the way I got around this problem was by setting up an empty single Drupal 6 site with the default D6 theme (Garland).  While it was still empty, I configured it and installed and enabled all the modules I was going to need.  Then I used Backup and Migrate to backup my content, and migrated that content (using Backup and Migrate) to the newly created and empty Drupal 6 monosite.

After the content was in place, I installed the the theme I wanted to use, and made it the default.

(I.e. the idea is to use Garland until everything else is OK.)


Entity id availability in Custom Field I've created a Custom Field (let's call it 'Reference') whose value requires the Entity Id.

To accomplish that I modify the Field value in the postSave method, like this:

if (!$update) {
  $this->get('value')
    ->setValue($this->getCalculatedReferenciaValue());
}

public function getCalculatedReferenciaValue() {
  //...
  $entity = $this->getEntity();
  $id = $entity->id();
  $year = date("Y", $date);
  // default format: 'SWAN%s%08dIMOV'
  $format = $this->getSetting('format');
  return sprintf($format, $year, $id);
}

Then, in pathauto, I use that custom created field, as a token, to generate the path.

However, for some reason, when creating a node, my custom field still has the default value.

If I then edit and save the node, the custom field (and the auto path) is updated correctly.

Q: Is there a way to update the field value so that it becomes available when generating the autopath for the first time?

For getting the node ID you need to first save the node. For eg:

$node = Node::create([
      'type' => 'my_content_type',
      'title' => 'My Title',
      'uid' => \Drupal::currentUser()->id(),
      'status' => 1
]);
$node->save();
    :
    :

$id = $node->id();
$year = date("Y", $date);
// default format: 'SWAN%s%08dIMOV'
$format = $this->getSetting('format');
$node->field_custom->value = sprintf($format, $year, $id);
$node->save();


Force block page to use admin theme? I'm trying to use this snippet I found, but it throws this error:

function mytheme_init() {
  // Hardcode the administration theme onto the blocks page
  if ($_GET['q'] == 'admin/build/block') {
    global $theme;
    $theme = 'rubik';
  }
}

Fatal error: Unsupported operand types in /var/www/clients/client4/web39/web/modules/block/block.admin.inc on line 39

The $theme = 'rubik'; line appears to be the culprit in some way, as it doesn't throw the error if I comment it.

You have to use the global variable $custom_theme.
The implementation of your hook_init() is good.


How to filter view by actual name of logged in user matches field? I'm using Drupal 7 and latest Views. I have a static field set with a variety of names, for a specific view I want to filter if the name of the logged in user matches the actual name of logged in user.

For example if logged in user is "Jean Claude" and I have a field with:

Big Sky,
Orange Cat,
Jean Claude

I would only want to display the content the field set to Jean Claude.

Using this post: Views: Filtering nodes on the basis of logged in user role
I was able to filter with contextual filter based on php query for current user


creating custom panes for field data in drupal 7 I need to port a panel feature from drupal 6 to drupal 7. I am able to get all the panel fields that come from views and blocks. Only thing i am not able to get is the fields that are coming from the content types.

Editing the panel shows "This pane's content type is either missing or has been deleted. This pane will not render." in the pane. The code generating this pane is

$pane->css = array();
  $pane->extras = array();
  $pane->position = 2;
  $display->content['new-4'] = $pane;
  $display->panels['top'][2] = 'new-4';
  $pane = new stdClass;
  $pane->pid = 'new-5';
  $pane->panel = 'top_left';
  $pane->type = 'content_field';
  $pane->subtype = '<field name>';
  $pane->shown = TRUE;
  $pane->access = array();
  $pane->configuration = array(
    'label' => 'inline',
    'formatter' => 'default',
    'context' => 'argument_nid_1',
    'override_title' => 0,
    'override_title_text' => '',
  );

The content_field type requires a plugin content_field.inc which was present in cck module in drupal6 as 'cck/includes/panels/content_types/content_field.inc'. How do i port this thing in drupal 7. There should be something equivalent to content_field.inc in drupal7
also.

Can someone lemme know how to get over this issue?

Thanks

Got his one. We need to replace content_fields with entity_+fields in drupal 7 as the content types are entity type in drupal 7 now.

Thanks


How do I render multiple form fields select boxes in a single row I am trying to render three dropdown boxes to be on the same line using a tpl file. Here is the snippit of code I am trying to work with:

$form_stuff = array();
$form_stuff[]=$form['field_list_1'];
$form_stuff[]=$form['field_list_2'];
$form_stuff[]=$form['field_list_3'];
print drupal_render($form_stuff);

I have also tried:

print drupal_render($form['field_list_1'] . $form['field_list_2'] . $form['field_list_3']);

Both will render each field element on a separate line.

This gets me a little closer but the dropdown renders on top of the label. It there a way to insert a
 after the label renders or some sort of style=display:block?

print '

';
print '' . drupal_render($form['field_list_1']) . '	';
print '' . drupal_render($form['field_list_2']) . '	';
print '' . drupal_render($form['field_list_3']) . '	';
print '

';

Thanks

In this, there is nothing to do with the coding part.
When we add a field it adds lot of wrapper div tags around it. And div tags has the by default property to take the next line in the page.

Just write some css for these divs.

<style>
    div.class1(display:inline-block;width:150px;float:left)
    div.class2(display:inline-block;width:150px;float:left)
    div.class3(display:inline-block;width:150px;float:left)
</style>

Hope it will work for you.


how to add a remove coupon button to commerce checkout page I assumed this would be included in the module, but as far as i can see it isn't. Im using the latest versions of Commerce, Rules, and Commerce Coupon.

I want a "remove" button next to the added coupons in case someone wants to remove it and try another one.

I was not able to recreate your issue. 'Remove' button was available next to the applied coupon.

The version of coupon code, I'm using is 7.x-2.0-rc2.

The steps I took were:

Added a discount and associated a coupon code with it.
Added an item to cart and checked out.
After confirming checkout was given option to add coupon code.

Checkout settings:

Note:

  The problem could be with checkout page. You can use order_coupon_list
  view block below the coupon code apply form.


Perfomance problem when posting Sometimes when I submit a new post (story node) or update one, it take 10-15 minutes for the page to finish loading. I figured it was some problem with the database so I did a SHOW FULL PROCESSLIST the next time I noticed it happening. It was stuck deleting from the boost_cache_relationships table. Why is this taking so long and what can I do to fix this?

Here's part of the output from SHOW FULL PROCESSLIST showing the problem query:

+---------+---------+-----------+-----------------+---------+------+----------------+------------------------------------------------------------------------------------------------------+
| Id      | User    | Host      | db              | Command | Time | State          | Info                                                                                |
+---------+---------+-----------+-----------------+---------+------+----------------+------------------------------------------------------------------------------------------------------+
| 2208461 | upgrade | localhost | dane101_upgrade | Query   |   28 | Sending data   | SELECT SUM(score) FROM search_index WHERE word = 'when'                                              |
| 2208478 | upgrade | localhost | dane101_upgrade | Query   | *1088* | updating       | **DELETE FROM boost_cache_relationships WHERE base_dir = 'cache/normal/www.dane101.com' AND page_callb**  |
|

It appears you may be having the same issue as this person - http://drupal.org/node/1136822

May I suggest you apply the tweaks mentioned in the issue, and if it improves your performance, perhaps consider writing a patch to place back in the issue queue.

I have cross linked the drupal.org issue with this, so that everything is visible


How to find the base table of view? A view is just an SQL query on a table - in the UI how can I find what table an existing view is based on?

Not exactly. But, you may find it helpful to goto Views -> Settings -> Advanced Settings from admin/structure/views and check the Show SQL Query in your View Preview.

Then goto a view and generate a preview and you will see the SQL statement Drupal is using to generate a query. Some parts of the Views lifecycle to render a views display though are fulfilled by PHP and not SQL. For example drupal Fields are inserted into each row of the the resultset if your display mode is either Fields or Rendered Entity. By this I mean the raw SQL does not perform a JOIN upon every field_data_* table used by your content type -- this is handled in PHP, and not SQL. All of this is also dependent on the Storage mechanism being used by Drupal (the default is SQL, but other backends exist such as NoSQL backends).

I'm just saying the SQL preview will show you ~70% of what Drupal is doing to generate your view. But there is some behind the scenes processing with sql metadata and hook processing going on too.


How to redirect user after form submit in overlay mode? The following code redirects user to node/add/article but doesn't use overlay.

$form_state['redirect'] = 'node/add/article'

How do I open node/add/article in overlay mode?

This seems to be the working solution:

Inside your form:

$form['somebutton']['#submit'] = array('your_custom_callback');

Add a custom callback

function your_custom_callback($form, &$form_state) {
  //redirect users to Drupal.org
  $url = "http://drupal.org";

  if (module_exists('overlay') && overlay_get_mode() == 'child') {
    unset($_GET['destination']);
    overlay_close_dialog($url, array('external' => TRUE));
    $form_state['redirect'] = FALSE;
  } else {
    $form_state['redirect'] = $url;
  }
}


How to debug a MySQL error? [Updated] I have been building a Drupal 7 site on my Mac. Using PHPMyAdmin, I have exported a sql dump of the database. When I upload this sql file to my host, I get the following error message:

There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem

ERROR: Unknown Punctuation String @ 280
STR: =,
SQL:

-- --------------------------------------------------------

--
-- Table structure for table `themekey_properties`
--

CREATE TABLE `themekey_properties` (
  `id` int(10) UNSIGNED NOT NULL,
  `property` varchar(255) NOT NULL DEFAULT '',
  `operator` varchar(2) NOT NULL DEFAULT=,
) ;

SQL query:

-- -------------------------------------------------------- -- -- Table structure for table `themekey_properties` -- CREATE TABLE `themekey_properties` ( `id` int(10) UNSIGNED NOT NULL, `property` varchar(255) NOT NULL DEFAULT '', `operator` varchar(2) NOT NULL DEFAULT=, ) ;

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=,
)' at line 10

How would I go about debugging this? I have searched extensively, but not found any websites that explain how.

The website functions perfectly on my localhost. I have done this process hundreds of times before, and never had any problems.

I seem to have this exact problem when transfering other sites from my Mac to my host, so I am not sure if it is a global problem. The affected sites all use themekey module which is referenced in the error message, but I can't find anything online which indicates why themekey would be causing the problem.

Updated.

I followed the @Erin McLaughlin's answer, but now I get the following error:

CREATE TABLE `themekey_properties` (
  `id` int(10) UNSIGNED NOT NULL,
  `property` varchar(255) NOT NULL DEFAULT '',
   `operator` varchar(2) NOT NULL DEFAULT '=',
)
MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 5

Updated.

I followed @Erin McLaughlin's second suggestions, but now I get the following error:

SQL query:

INSERT INTO `themekey_properties` (`id`, `property`, `operator`, `value`, `weight`, `theme`, `enabled`, `wildcards`, `parent`, `module`) VALUES
(1, 'themekey_compat:module_system_triggers_theme', '=', 'static', 5, 'default', 1, 'a:0:{}', 0, 'themekey'),
(2, 'drupal:path', '=', 'user/#/edit', 2, 'default', 1, 'a:0:{}', 0, 'themekey')
MySQL said: Documentation

#1054 - Unknown column 'value' in 'field list'

It has got to do with the line:

`operator` varchar(2) NOT NULL DEFAULT=,

It's because the equals sign isn't surrounded with a space and then quotes, which is breaking everything. If you want to have = be the default operator, that line needs to be:

 `operator` varchar(2) NOT NULL DEFAULT '=',


Updating core to a specific version with Composer My site hasn't been updated for two months, a few new updates has been released.
My site's core version is 8.5.6.
Before running composer update -with-dependencies I read the release notes to the latest version of core (8.6.2), they say:

  Sites on 8.5.x should update immediately to Drupal 8.5.8 instead, and
  plan to update to the latest 8.6.x release before May 2019.

How do I update the old core to Drupal 8.5.8 instead?
How do I specify that version in CLI, what command?
Eventually I want to update it to the latest version.

I was in the same position. I used :

composer require drupal/core:^8.5.10

And it worked. Cheers.


DRUPAL 7.33 - When i try to save a node with upload, i receive website encountered unexpected error...PDOException: SQLSTATE[25P02] In my postgresql log i have error on this select:

SELECT base.fid AS fid, base.uid AS uid, base.filename AS filename, base.uri AS uri, base.filemime AS filemime, base.filesize AS filesize, base.status AS status, base.timestamp AS timestamp, base.type AS type
    FROM
    file_managed base
    WHERE  (base.fid IN  ('resultadopdf_1'))

The file is uploaded, but the node not... I want to understand why the select compare a field id (integer) with a string...
Someone know where this select is made?

After aplied patch:

PDOException: SQLSTATE[25P02]: In failed sql transaction: 7 ERRO: current transaction has been halted , commands ignored until end of transaction block: SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_schema = :schema AND table_name = :table AND (data_type = 'bytea' OR (numeric_precision IS NOT NULL AND column_default LIKE :default)); Array ( [:schema] => public [:table] => node [:default] => %nextval% ) em drupal_write_record() (linha 7239 de /var/www/portalunifei/includes/common.inc).

But in then postgrelog shows:

ERRO:  input syntax for integer is invalid: "notaspng" at character 256
COMANDO:  SELECT base.fid AS fid, base.uid AS uid, base.filename AS filename, base.uri AS uri, base.filemime AS filemime, base.filesize AS filesize, base.status AS status, base.timestamp AS timestamp, base.type AS type
    FROM
    file_managed base
    WHERE  (base.fid IN  ('notaspng'))
ERRO:  current transaction has been halted , commands ignored until end of transaction block
COMANDO:  SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'node' AND (data_type = 'bytea' OR (numeric_precision IS NOT NULL AND column_default::text LIKE '%nextval%'))
LOG:  duração: 0.025 ms  comando: ROLLBACK

sorry for the delay, but finally found the solution to my problem ...
https://www.drupal.org/node/1003788

I would like to acknowledge the help of you gave me...


How Update item on the second page in WebForm wizard I am starting to work with webform in drupal 8 and I need to show values on the second page of the webform wizard, I have reviewed several solutions but I cannot do it. I tried using $ form_state-> setValue

function webform_certificadoemail_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {

  if ($form_state->get('current_page') == 'preview') {

    $value_entered = $form_state->getValue('nombre');
    drupal_set_message('Valor del nombre en el preview =:'.$value_entered);

     $form_state->setValue('valor','This value is .......'); // This not work
  }
}

When you are in the preview page, you're too late then.

You need to set this in your previous step in a validate function

function webform_certificadoemail_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {

   if ($form_state->get('current_page') == 'step_1') { // or whatever you called the first page
     $element['#element_validate'][] = 'webform_certificadoemail_set_valor';
  }

}

function webform_certificadoemail_set_valor($element, FormStateInterface $form_state) {
   $form_state->setValue('valor','This value is .......');
}


Service function is not calling I am trying to validate a key, which I am passing as url argument using service. But service function is not calling.

It's giving "Access denied" error. Am I missing something?

My sample code is:

cunn.routing.yml

cunnotification.saverecord:
  path: '/cunnotification/saverecord/{key}'
  defaults:
    _controller: '\Drupal\cunnotification\Controller\SaveRecordToDBController::SaveRecord'
  options:
    no_cache: TRUE
  requirements:
    _access_cunn_saverecord: 'TRUE'

cunn.services.yml

services:
  cunn.saverecord:
    class: Drupal\cunnotification\Access\CUNAccessCheck
    tags:
      - { name: cunn_access_check, applies_to: _access_cunn_saverecord }

CUNAccessCheck.php

namespace Drupal\cunn\Access;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Access\AccessResult;

/**
 * Access check for conn routes.
 */
class CUNAccessCheck implements AccessInterface {

  /**
   * Checks access.
   *
   * @param string $key
   *   The conn key.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access($key) {
   // Logic here
   return TRUE; // based on logic
  }
}

Don't change they tag name, just access_check:

services:
  cunn.saverecord:
    class: Drupal\cunnotification\Access\CUNAccessCheck
    tags:
      - { name: access_check, applies_to: _access_cunn_saverecord }


How to have an environment specific drush.yml? I'm using Drush 9. With the old drushrc.php I could easily include a local.drushrc.php that dynamically set the site url. How can I do it now?

This is similar to How can i set site url dynamically in Drush-9?. However I don't want to pass the url in every Drush command. I think of something like below in ../drush/drush.yml:

drush:
  paths:
    config:
      - ${env.home}/local.drush.yml

But I'd need another variable that point to the Drupal site directory (sites/default in a monosite, sites/CURRENT-SITE in a multisite). Does such a variable exist?

Reading https://github.com/drush-ops/drush/blob/master/examples/example.drush.yml it seems you can put a site specific drush.yml in a sites directory. It is merged with the global file(s).

PS! I haven't tested this myself.


How to use the dsm( ) Devel function to print the $form array of my form? I want to use the dsm() function of the Devel module to print the $form array of a form, where the form_id is search_theme_form. How to do that?

Start a custom module, insert this code:

/**
* Implements hook_form_alter().
*/
function foo_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'search_theme_form') {
    dpm($form);
  }
}

Also, you might want to use dpm() over dsm() since the latter is a legacy function.


How can I resolve my CGI error during installation of Drupal 7 on WinXp? I'm installing a local instance of Drupal 7 on my WinXp machine. PHP 5.4 and MySql 5.5 are installed already.

I've unpacked the downloaded Drupal 7 site files into a virtual directory and used IIS 6 to make this directory a PHP site.

However, the result is not encouraging:

  CGI Error The specified CGI application misbehaved by not returning a
  complete set of HTTP headers. The headers it did return are:

  Could not open input file: Files\PHP\php-win.exe

The web address I'm using is:

http://localhost/drupal7/install.php

Where "drupal7" is the name of my application in IIS.

Any ideas on what the problem might be?

As in my comment above, you should try using WAMP server or Acquia Dev Desktop, which uses Apache (more suitable for PHP development).

To install Drupal on Windows, you could install it with Microsoft web platform installer by following this procedure.


How to programmatically create entity with certain language applied to fields? I am programmatically creating some content during profile installation and since Drupal uses "en" langcode during this period I am getting the language from config and it is working fine.

The issue I have is that I am creating a node and I will end up with it being in English. So I have set the "langcode" property of the node during creation which worked as expected. But the fields are not responding to this fact(I have only the body field attached).

So I have tried to key the value(s) by the langcode(Drupal 7 style) but it resulted in the field not being populated in DB at all.

The node entity nor field item list nor field item have methods for setting the langcode so I am unsure how to proceed with this.

Any ideas?

This is my code:

// Create 'terms of service' page
  $tos = entity_create('node', [
    'type' => 'page',
    'title' => t('Terms of service', [], ['langcode' => $langcode]),
    'uid' => 1,
    'status' => 1,
    'langcode' => $langcode, // this is working on node only
    'defaultLangcode' => $langcode, // no change on field
    'activeLangcode' => $langcode, // no change on field
    'body' => [
      $langcode => [ // this is not working
        [
          'value' => '<p>' . t('This is a placeholder. Please edit this page and use your own text.', [], ['langcode' => $langcode]) . '</p>',
          'summary' => '',
          'format' => FULL_HTML_FORMAT
        ]
      ]
    ]
  ]);
  $tos->save();

I have found setLangcode() method on the FieldItemList but that didn't work as well.

I have tried to save the node without body, then set the body and save the node again, but the field is in English again(and the node in installed language). Is it possible that this is kind of a (edge case)bug that relates to language manager?

I have checked the entity constructor and this is also not working:

'body' => [
      $langcode => [
        [
          'value' => [
            'value' => 'some text',
            'summary' => '',
            'format' => FULL_HTML_FORMAT
          ]
        ]
      ]
    ]

I have found a solution.
As I have mentioned this was during the profile installation process and it is related to How to get correct language code during installation?

The solution was to make sure the installed language exists before the modules are being installed and set it as default. Normally, translation are the last installation task. So I have copied the following code from install_download_additional_translations_operations() into a task in my profile that runs before modules are installed.

if ($langcode != 'en') {
    \Drupal::service('module_installer')->install(['language']);
    if (!($language = entity_load('configurable_language', $langcode))) {
      // Create the language if not already shipped with a profile.
      $language = ConfigurableLanguage::createFromLangcode($langcode);
    }
    $language->save();

    \Drupal::service('language.default')->set($language);
  }

I have also removed the $langcode from my code since translations were now working as expected.


Can a database serve two different installations on localhost? I have a Drupal 6 live site backed up to my localhost and I want to transition the localhost version to 7 before uploading to become the live site.

In my mind the ideal process would be to have a separate 7 install accessing the same (or mirrored) database so I still have a clean 6 backup in case of trouble with the live site. Does anyone have an opinion if this possible and/or the best way to do it?

I have MAMP Pro driving the localhost.

There is no problem using a single database to serve multiple applications (including multiple Drupal instances).  However, they need to be completely separate instances. You cannot use a Drupal 6 database instance as part of a Drupal 7 instance.  You must set up a clean Drupal 7 instance, and then migrate the content from a Drupal 6 instance into it, using the standard procedures for upgrading from Drupal 6 to Drupal 7.

To do this, you use something known as "table prefix".  When you install Drupal (both 6 and 7) on the database setup page you get during installation, you can expand a tab to get to Advanced options.  This gives you access to some extra options, including "table prefix".

The "table prefix" allow for multiple instances sharing the database.  For instance, if your existing Drupal 6 site is set up without a table prefix, you can use the table prefix d7_ to set up a Drupal 7 configuration in the same database that will not interfere with your Drupal 6 configuration.


How do I treat the phrase as individual words in Search? I have a problem in our Search results. We are using Search API and Search API Solr modules running in drupal 8.

We have successfully indexed our content in Solr and is pretty working.

For example, I have a term called "Jakarta Law firm" and it will display the results like: Jakarta Law Firm in 2000, Jakarta Law Firm in 2001, etc.

However, if I searched "law firm Jakarta", it will return no results. Can you please tell me if there are any configurations in Solr or in the module so that it will search whatever the order of the search words? Or may I know what is the Solr term functionality that will handle that? Or any hooks that we can use?

I really appreciate your help about this!

When adding text fields to your search index, you need to indicate it's usage by specifying if you want it to be a Fulltext field or a String field.

You can add the field twice, once a String and once as a Fulltext field.

If you are using views, you'll want to make sure your full text search exposed filter includes the Fulltext version of this field, and is set to "Contains any of these words"


How to omit form's validation at AJAX button click? I have an AJAX button that should update form fields according to data already provided by user:

 'ajax_button' => array(
    '#type' => 'button',
    '#value' => t("Scan for tags"),
    '#ajax' => array(
      'callback' => 'ajax_tag',
      'wrapper' => 'dynamic-tags-fieldset',
      'method' => 'replace',
      'event' => 'click',
      'prevent' => 'submit click mousedown',
    ),
  ),

It works, but only if form is valid. Of course I do not want to validate it just yet. I don't care if all fields are filled, I only need my form to be updated at this very moment. How can I make form api not to invoke hook_form_validate() and not test #required fields?

You can use the #limit_validation_errors property:

  Provides an array of sections which are parts of $form_state['values'] which should be validated, implying that sections which are not listed should not be validated. This is normally used in multistep forms in the case of a "back" button, for example, where '#limit_validation_errors' => array() would mean not to validate anything as form values on the current page are to be discarded anyway. #limit_validation_errors does not have any effect if #submit is not set. More discussion is in the form_set_error() documentation.

e.g.

'ajax_button' => array(
    '#type' => 'button',
    '#value' => t("Scan for tags"),
    '#ajax' => array(
      'callback' => 'ajax_tag',
      'wrapper' => 'dynamic-tags-fieldset',
      'method' => 'replace',
      'event' => 'click',
      'prevent' => 'submit click mousedown',
    ),
    '#limit_validation_errors' => array(), // No elements will be validated
    '#submit' => array('custom_function'), // An explicit submit functions array is required for this, but may be empty
  ),

However, each validation function is free to respect '#limit_validation_errors' or not. If you want your validation functions to respect this parameter, you need to:

Obtain #limit_validation_errors value from clicked button using $form_state['clicked_button']['#limit_validation_errors']
Pass it as a third argument to each form_set_error() call


There is no register form but spams are sending register request in Drupal 7! There is no register or login form in front-page or any other pages in my website but every day I receive emails of my website that some people asked for registration, How does such a thing is possible and how do they do this?

Go to admin/config/people/accounts
and configure : Registration and cancellation for administration only


How to hide text format options when using WYSIWIG module? Using this tip I was previously hiding the text format options with

$form['und'][0]['format']['#access'] = FALSE;

When I enabled WYSIWYG it wouldn't show the editor and I had to use

$form['und'][0]['format']['format']['#access'] = FALSE;
$form['und'][0]['format']['guidelines']['#access'] = FALSE;
$form['und'][0]['format']['help']['#access'] = FALSE;

What's left now is this bottom box (below Path: p...)

This is the HTML that's generating it:

<fieldset class="filter-wrapper form-wrapper" id="edit-comment-body-und-0-format">

<input id="edit-comment-body-und-0-format--2" class="wysiwyg wysiwyg-processed" type="hidden" name="comment_body[und][0][format]" value="filtered_html">

</fieldset>

I could hide it with CSS. How would I hide it with code similar to above? Btw, I'm aware of Better Formats module but don't want to use it just for that.

Try unsetting the field elements. According to the blog post this kills TinyMCE

<?php
  function [theme_name]_form_comment_form_alter(&$form, &$form_state, $form_id)
  {
    $form['comment_body']['#after_build'][] = 'remove_tips';
  }

  function remove_tips(&$form)
  {
    unset($form['und'][0]['format']['guidelines']);
    unset($form['und'][0]['format']['help']);
    return $form;
  }
?>

source: technonaturalist


flowplayer - stream from file:///fodler/video.flv possible? I have converted my made in drupal into HTML with blue crab (spider)
I have to give to my clients a USB stick with the site made in drupal and all pages have to work

there is only one problem
- the videos won't work offline
Does flowplayer only work with a HTTP server??

Flash video has problems playing from some local URLs in Windows, but it mainly has to do with network shares.  The workaround is to map the share to a drive letter.

You may also be having problems with local file access versus network resource access.  Google "flash player security restrictions" for an overview.  With the Flowplayer SWF, you are likely out of luck for working around this w/o getting users to change security settings.

The best option is to use a local web server.  With this you may even be able to get Drupal running off of your memory stick.  There are several options, but I have had good luck with Server2Go.  I have never used it with Drupal, though.


Require visitor to fill a form to view contents How can I require visitors to fill in a form if they want to view certain pages?

I don't have experience with the Webform module, but I think that you could create a rule to grant access to a referenced node when the user submits the form.

Basically, you need to add an entity reference field to the webform content type, reference the webform with the particular node, and create a rule that on the form submission event grants the current user access to the referenced node.
In Content Access and ACL, you should set the access per-node and per-user.

You'll need Entity reference, Webform, Rules, Webform Rules, Content Access and ACL modules.


ckeditor issue while ajax submit i m using ckeditor in a form that submits through ajax. when the submit is clicked and the submission is in progress my ckeditor converts into a plain text editor and all the controls are gone, as soon as the submit is complete, the controls are back, it looks ugly. Any solution?

though the solution looks temporary but i see no bugs in it. The solution is to comment the line:

CKEDITOR.instances[textarea_id].destroy(true);

under ckeditor.utils.js

More better option would be to put a condition to skip the destruction of ckeditor instance


Where can I find the upcoming DrupalCamps and DrupalCon? Where can I find the upcoming DrupalCamps and DrupalCon ? I'm not aware of any website that contain information about  upcoming DrupalCamps and DrupalCon other than social media. I think will be nice if I can have a page where I can see upcoming DrupalCamps and DrupalCon.

I have always enjoyed http://www.drupical.com/
It takes a direct feed from http://groups.drupal.org/events


Webform new line after the field name I have created my first webform in drupal 8. However, I found that some of the fields such as "Telephone", "Email" are showing the field name and the textfield on the same line. However, for the text field such as "Name" and "Subject" (Also a textfield), the field name and textfield are showing on different line.

I haven't done any setting on those 4 fields. I would like to ask if I could do some settings such that the textfield is always under the field name?

Thank you for your help.

Telephone and Email are field which looks like textfield but actually are not of type textfield. Instead, they are of field type telephone and email respectively, which was introduced when Drupal 8 was released.

In order to show field title and field input in same line use below steps,

Edit the individual field.
Go to form display setting and open the title display dropdown.
Select Inline option.


Create a view/list of pages made with Panels I know how to view/list particular content types in a View:

I just need to add a "filter criteria" to the View that will display all node belonging to that type.

cool. but, I can't figure out how to view/list particular pages made with Panels.

Pages made with Panels are not selectable from the "filter criteria" box in the View.

Try www.yoursite.com/admin/structure/pages

This lists all the system generated & custom panel pages that exist.


Switch to Drupal Mobile Theme Programatically I found the following code on http://detectmobilebrowsers.com/ and would like to use it to programatically switch from my default theme to a mobile theme that I will also have active.

<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))) {
    //Change Drupal theme to a custom mobile theme
} else {
    //Continue assigning the default theme
}
?>

Where should I place this code so it will transparently use the correct theme? I don't want to use another module or a sub domain for the mobile site. I just want to use a different theme for users accessing my site from their mobile phones. Thanks!

The best option out there is to use module themekey that has all the tweaks to detect the user browser and serve the right theme. The performance hit is un-noticeable and it has already done all the hard work for you already.

Check a nice tutorial here: http://mustardseedmedia.com/podcast/episode52


'reversed' node refs? Here is the current situation:
i have an artist database and users can 'like' the artist with a flag button and that works great, but i need to use the 'like' data to get some other info

Case:
1. user likes artist(flag!)
2. user logs out
3. user returns to website and logs in and gets redirected to custom page

4. The custom page needs to contain nodes that reffer to the artist.

Its step 4 where i got stuck, i just don't know how to display the information from B to A in a view?

Using Drupal 6 and views 2.

Thanks!

In views edit > Relationships > add Flags: User's flagged content (also select Include only users who have flagged content.)