texts: How do I create a Url object from the public file URI?

texts:
How can a Url object be created from a file URI? Using the URI for a public file as a parameter for Url::fromUri() gives this error.

  UnexpectedValueException: External URLs do not have internal route parameters. in Drupal\Core\Url->getRouteParameters().

$file = File::load($file_id);
$file_uri = $file->getFileUri();
$menu_link['url'] = Url::fromUri($file_uri);

Here is the class and method in question:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromUri/8.2.x

Note that I don't need to get the actual URL in string format, I need to generate a Url object from the Url class that points to a file. This is because I am attempting to modify the path of a menu link and unfortunately that is not a simple matter of providing a URL string in Drupal 8.

This is the code I am using.

function teeprop_preprocess_menu__main(&$vars) {
  foreach($vars['items'] as $key => $menu_link) {
    if (!empty($menu_link['url']->getRouteParameters())) {
      $node_id = $menu_link['url']->getRouteParameters()['node'];
      $node_entity = Node::load($node_id);
      $node_type = $node_entity->getType();

      if ($node_type == 'pdf') {
        $file_id = $node_entity->get('field_pdf_file')->getValue()[0]['target_id'];
        $file = File::load($file_id);
//         $file_url = $file->url();
        $file_uri = $file->getFileUri();
        $vars['items'][$key]['url'] = Url::fromUri($file_uri, ['absolute' => TRUE]);
      }
    }
  }
}


texts: Modify Override the Views Filter Criteria Programaticly

texts:
I have the following view being called in my code with views_get_view() and I then try to modify the filter called usershare to admin instead of the default that I have set in my view. But it doesn't seem to override my view output. What am I doing wrong here? I noticed that some examples use pre_execute() and some just use excute(). I'm not sure if that has anything to do with it.

      $view2 = views_get_view('flag_lists_user_lists_public', FALSE);
      $view2->set_display('default');

$view2->display_handler->display->display_options['filters']['usershare']['value'] = 'admin';

      $view2->pre_execute();
      $output .= $view2->render();


texts:
We would like to give admin users of a custom theme the ability to set a color palette for each content-type for all visitors to a site.

The color module gives a way to allow admin users some control of a single color palette for the whole website but we want to let them set a palette for each content type (or leave the base color theme for each). Including any new content types, they may create in the future.

Is this feasible?

I have been poking around the color module but I am not sure how hard it would be to write a custom module that extended it in this way. Any ideas if this is even possible?

This is for a Drupal 8 site and theme.


texts:
I have a problem with entity URLs in D8. All of them are absolute instead of relative, which causes various problems. For example,link URLs to edit content on /admin/content look like this:

http://example.local/node/693/edit?destination=http%3A//example.local/admin/content

instead of

/node/693/edit?destination=/admin/content

It's not theme-related issue
I checked various custom classes implementing OutboundRouteProcessorInterface and it seems, that none of them should affect this

What could be the cause, then?

EDIT: It's the same with all Drupal-generated links.

BTW. The issue can be seen by executing

use Drupal\Core\Link;
$link = Link::createFromRoute('This is a link', 'entity.node.canonical', ['node' => 1])->toString();
print_r($link);

It should result in relative URL, in my case it's absolute one.


texts: If Profile2 fields are empty, problem in accessing data

texts:
I just found out that if ALL fields of certain Profile2 profile ie. main are empty, I am not able to access data inside main profile. For example I want to do a check if a field is empty but can not access it using

global $user;
$account = user_load($user->uid);
$data = profile2_load_by_user($account);

How can I access the fields? thank you.


texts: How do I use a newer version of jQuery with Ubercart shipping quote (Ajax)?

texts:
If I use any version of jQuery with drupal/ubercart other than jquery 1.2.6, the ajax comes back from (UPS,Fedex,etc), but never updates the objects on the screen.

How do I use a more current version of jQuery with ubercart?


texts:
I've created a custom widget for a textarea (to display the contents in a table as well). So the textarea should appear and work just like a normal textarea widget, but with an additional HTML table of its contents.

I can make it appear correctly, but when I save the form the values do not get saved.

In fact, my "data_source_field_is_empty()" function is never called (the dpm() text never appears).

function data_source_field_widget_form(&$form,
                                         &$form_state,
                                         $field,
                                         $instance,
                                         $langcode,
                                         $items,
                                         $delta,
                                         $element) {
  switch ($instance['widget']['type']) {
    case 'data_source_data_widget':
      $thisItem = isset($items[$delta]) ? $items[$delta]['value'] : '';

      $widget['#type'] = 'textarea';
      $widget['#default_value'] = $thisItem;

      // Only do this if there is already content in the field
      if (isset($items[$delta])) {
        $rows = _data_source_parse_csv($thisItem);

        $widget['#prefix'] = '<button type="button" id="show-hide-raw-table-data">Show raw data</button>';
        $widget['#suffix'] = _data_source_dataTable($rows, 0);

        $form['#attached']['js'][] = array(
          'data' => drupal_get_path('module', 'data_source') . '/js/data_source.js',
          'type' => 'file',
        );
        $form['#attached']['css'][] = array(
          'data' => drupal_get_path('module', 'data_source') . '/css/data_source.css',
          'type' => 'file',
        );
      }

      $element[$field['field_name']] = $widget;
      break;

  }

  return ($element);
}

function data_source_field_is_empty($item, $field) {
  dpm("Got here");
  return empty($item[$field['field_name']]);
}

Any ideas? I'm looking at the $element[$field['field_name']] = $widget; part, but none of the variations I've tried have worked.


texts:
I want to update a node field's value when a node is updated.

Tried using the code mentioned here Programmatically updating a node Drupal 8

use Drupal\node\Entity\Node;

    function hello_world_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

      $check = \Drupal::routeMatch()->getParameter('node');

      if ($check) {
      $node = Node::load($check->nid->value);
      $node->title->value = 'testing';     //set value for field
      $node->save();
      }
    }

but it did not work. I get a 500 error after saving the node. I also tried taking out the if statement and specifying a node id $node = Node::load(1);

I also tried using Update a node / Entity programmatically in Drupal 8

use Drupal\node\Entity\Node;

function hello_world_node_update(Drupal\node\NodeInterface $node) {

$node = Node::load(1);
$node->set("title", 'New value'); // also tried $node->setTitle('The new Title');
$node->save();

}

but no luck either.

In addition, I tried using different hooks entity_presave, entity_update, node_update, but did not make any difference.


texts: How to set a Rules Condition "Does this node with date field use repeating functionality"?

texts:
I want to set a condition based on whether a calendar item (node that uses a date field) has repeating values set.

I can't find anything relevant in the data selector. The rule event includes "content of type" so it's not an issue related to "entity has field." The relevant field is showing up in the data selector.

Also, in addition to wanting to determine "is this a repeating date", I'd want to get access to the repeat rule (by this "rule" I mean the rule created by the date module, not the Rules module). I see no data selector for that either.


texts: why are users logged out after 2 days of not logging in

texts:
We got LDAP SSO working for our site. Employees go to the site everyday and everyday they do not have to input their credentials... until Monday. I believe this has to do with cookies maybe? I think if the employees have not logged in in a couple of days (weekend) then they have to log back in. Every Monday they have a http authentication dialogue box (LDAP Authentication from the /user/login/sso url). It saves their credentials (if they hit remember my password), but they don't like hitting the enter key.

My /admin/config/people/ldap/authentication settings look like this:

I then found this post: Why is session.cookie_lifetime set to 23 days?, where they say that in drupal it might have a session.gc_maxlifetimesetting in settings.php that is set to 23 days, but that the session.cookie_lifetime is set to 2.3 days. And that if the user doesn't visit the page withing 2.3 days then they start a new session or something. Does this mean if I adjust the ini_set('session.cookie_lifetime', 200000); to like 4 days that the employees wont need to hit enter anymore?


texts: Simpletest on select field loaded by ajax

texts:
I have searched through Google and haven't found an answer. Stack Exchange is my last resort.
In my form, I have two select fields:
$form['system']['foo'] = array(
  ...
  '#type' => 'select',
  '#options' => array('A', 'B', 'C'),
  ...
  '#ajax' => array(
    'event' => 'change',
    ...
    'method' => 'replace',
  ),
);

$form['system']['bar'] = array(
  ...
  '#type' => 'select',
  '#options' => array(),
  '#prefix' => ...
  '#suffix' => ...
);

If user selects any of the options in foo field, the bar field dynamically loads the options through ajax. Example: If 'A' is selected on foo, bar field generates options like 'aaa', 'bbb', 'ccc' and can be selected by the user.
This form works and I need to provide its unit test using 'Simpletest'.
On my test case:
$edit = array(
  'system[foo]' => 1, // value for 'A'
  'system[bar]' => 2, // value for 'bbb'
);
$this->drupalPost('mymodule/mypath', $edit, t('Submit'));

gives an error saying system[bar] cannot be set to 2 (because it has no value of 2 yet?)
I need to emulate ajax call on system[foo] before setting system[bar].
I have tried drupalPostAjax:
$edit = array(
  'system[foo]' => 1, // value for A
);
$this->drupalPostAjax('mymodule/mypath', $edit, 'system[foo]');

and gives me a success result on ajax. On the next lines of code, I tried calling drupalPost() again using the previous code snippet but gives me the same error saying system[bar] cannot be set to 2.
How can I solve my problem? Please provide sample code as it can help me a lot..

EDIT:
Ajax works on the actual page (i.e the values are dynamically loaded to system['bar']). So I can assume my code in the forms is working.
However, I just noticed that ajax does not work on the generated page from Simpletest (the one found in sites/default/files/simpletest/verbose). Console from Google Chrome does not show any errors. Ajax returns status 200 but does not have any response.
I am using the default theme upon installation.

EDIT: The form and simpletest code
The form: I copied the form posted by znerol.
The simpletest code:
class MyModuleTestCase extends DrupalWebTestCase {
  protected $admin_user;

  public static function getInfo() {
    return array(
      'name' => 'Test Case name',
      'description' => 'Test Case Description',
      'group' => 'My Module',
    );
  }

  public function setUp() {
    // Enable module
    parent::setUp(array('mymodule'));

    // Get permissions
    $permissions = mymodule_get_permissions();
    // Permissions obtained correctly.

    // Create and login admin user
    $this->admin_user = $this->drupalCreateUser($permissions);
    $this->drupalLogin($this->admin_user);
  }

  // Test section
  public function testSystem() {
    $this->drupalGet('mymodule/mypath');
    $edit = array(
      'system[foo]' => 1, // Selects 'A'. Tested!
    );
    $this->drupalPostAjax(NULL, $edit, 'system[foo]');
    // Bar after ajax is loaded
    $edit = array(
      'system[bar]' => 1, // Selects 'aaa'
    );
    $this->drupalPost(NULL, $edit, t('Submit')); // Error here.
    $this->assertText(t('Submitted!'));
  }
}

However, when running simpletest, simpletest complains that system['bar'] cannot be set to 1 (aaa).
I have noticed simpletest shows the following warning before it calls ajax.

Undefined offset: 0 Notice drupal_web_test_case.php 2147 DrupalWebTestCase >drupalPostAJAX()
Undefined index: Notice drupal_web_test_case.php 2148 DrupalWebTestCase->drupalPostAJAX()
Undefined index: #ajax Notice ajax.inc 379 ajax_form_callback()

Since system['bar'] is loaded dynamically through ajax, it has an empty array initially array(). From the warning above, I tried adding a temporary option array('1', '2') in system['bar']. The same error and warning occurs.


texts:
My Drupal installation has some warnings, I tried several patches, but none of them works for me. These are the warning messages:

Warning: Invalid argument supplied for foreach() in taxonomy_field_formatter_prepare_view() (line 1677 of modules/taxonomy/taxonomy.module).
Warning: Invalid argument supplied for foreach() in taxonomy_field_formatter_view() (line 1600 of modules/taxonomy/taxonomy.module).

It looks like I get those warnings randomly, I can't find a specific handling.
I think I get this message when I create/edit a node.


texts: How to set a new password using a module?

texts:
I'm sending out mails to existing users telling them their username and password with tokens.

Because there is no way to access the user's password (fortunately!), I'm simply setting a new password. But It seems not to work at all.

This is what I've tried so far:

// Include the password.inc file to use hashing functions
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

// This is my user account (dummy function)
$account = get_some_user();

// Generates new random password of length 12
$password = user_password(12);

// Prepares the new user object and hashes the password
$edit = array();
$edit['revision'] = 0;
$edit['pass'] = user_hash_password($password);

// Saves the user object
user_save($account, $edit);

// Do stuff with password...

But this does not really work. The password hash gets changed in the $account[pass] field, I've checked that, but I can't login using the new password.

What did I miss?


texts: Maintaining the integrity of URLs while moving pages between site sections in Drupal 7

texts: Could anyone please tell me how does drupal 7 handle urls when moving or reordering the pages within and between the sections witithin the site. Is it possible to preserve the urls or not?


texts:
I am using PepiPost mail service and I created custom mail system class for integrating PepiPost service. I can successfully send email from Drupal site. If a connection timeout 504 occurs during email sending process, email is not triggered how can I handle this scenairo. This is the code I used for email sending

class CustomMailSystem implements MailSystemInterface {

  public function format(array $message) {
    // Join message array.

      $message['body'] = implode("\n\n", $message['body']);
      return $message;
  }

  /**
   * Implement mail method to send mail via Sendgrid.
   *
   * @param array $message
   * @return bool
   */
  public function mail(array $message) {
    $email = new Email();

    $data = array(
      'api_key'   =>  '****************',
      'recipients'    =>  $to
      'email_details' => array(
        'from'          =>  $from,
        'subject'       =>  $subject,
        'content'       =>  $body,
    ),

  try {
    $response = $email->sendJson( $data );

  catch(Exception $e){
      print 'Call failed due to unhandled exception/error('. $e->getMessage().')'."\n";
    }
  }
}


texts: How to load .css file only on your custom 404 Not Found page?

texts:
Following this guide I created a custom page--404.tpl.php page for my custom 404 Not found page. We put this in template.php:

function themename_preprocess_page(&$vars) {
 // Adds a Custom 404 page
 $header = drupal_get_http_header("status");
 if($header == "404 Not Found") {
   $vars['theme_hook_suggestions'][] = 'page__404';
 }
}

Now I need to load CSS only when that page is loaded. This here only shows how to load it in either node or front page, but not custom 404 page.

This does not work:

    $header = drupal_get_http_header("status");
    if($header == "404 Not Found") {
      $vars['theme_hook_suggestions'][] = 'page__404';
      drupal_add_css(drupal_get_path('theme', 'dev') . "css/404/bootstrap.css");
      drupal_add_css(drupal_get_path('theme', 'dev') . "css/404/custom-style.css");
    }

}


texts:
This is the profile page http://www.lusciousanime.com/users/ruriko
You notice there 2 duplicate profile pictures. I am using panels to layout the profile page. On the left column it uses Author Pane and the right column it uses User Profile token. I am also using Profile2 module. I want to remove the picture in the right column. How can I do this?


texts: Use MenulinkTree::load in page_preprocess

texts:
I'm on drupal 8, and i want to get menu links from the main menu in order to create the same menu for mobile (so i need 2 same menu, with differents rendering)

I use like this :

function template_preprocess_page(&$variables) {
    $variables['menu'] = \Drupal\Core\Menu\MenuLinkTree::load('main');
}

But it's broke my website.

What do you think about that ?


texts: How to automatically populate a field with a value part of another field

texts:
I will try to be as specific as possible.

I have a required text plain field in a content type, say 'field_A'.  This will have values of minimum 2 words, maximum 5 words. Words will be separated by spaces.  I can be certain of this.

What I want, is to have another field, say 'field_B' in which I want to keep the last word of field_A.  I would like this to happen automatically (upon creation of a node of this type).

I have no idea if this is possible ...

So, say I 'm adding new content of this type, and use value "lorem ipsum whatever" for field_A, upon submitting I would like the word 'whatever' to be inserted as a value in field_B.

I 'd be grateful of any help ..  I couldn't find relevant info on this, it's kinda hard to describe in a few words.

Working on D8.


texts:
I manage this website wich was built by somebody else. The client wants me to implement some google tracking codes on several webform confirmation pages.
These webforms call the confirmation message using ajax.
The webform has the redirect settings set to: stay on the same page and the webform is made availible as block.

Normally (without ajax) I would just make a new tpl using this naming format: webform-confirmation-[nid].tpl.php , but that doesn't seem to work because of the usage of ajax.
I have also tried to put the tracking codes inside the confirmation message textarea in the webform backend. but then the message didn't load at all.

So I guess my question is how do I get the ajax to grab my custom template?


texts: Add mini pager and infinite scroll to a view

texts:
I have a view where at first 1 item has to show. On click of 'load more' next item has to show and so on. For this i have installed 'infinite scroll module' in drupal 8. Now after showing four items, 'load more' has to change to ' show less' and hide all four items. I am not sure how to do this as infinite scroll module doesn't have this option.

Also, once there are four items are displayed, pagination with 'next' (on click showing next 4 items) has to appear.

I am not sure how to do this. Any help will be appreciated.


texts: How can I filter a view by date ranges from another content type?

texts:
I am building a site in Drupal 7 that has a list of events.  I would like to be able to filter these events by specific date ranges from another content type.

I have successfully been able to set up a view that enables users to filter the list of events by a number of criteria including an arbitrary date range. That much is fine.

However, I would like to allow users to filter the events into date ranges that come from another content type.  In this particular case I want the site to show events that occur within the term of office of UK prime ministers.  I have set up a content type that has the start and end dates of the term of office of the prime ministers but I can't see how to use this to filter the events.

Ideally I would like a drop down list that allows the user to select a prime minister and this will show a list of events that occur during that prime minister's term of office.

How would you suggest that I do this?

Thank you in advance for your help.


texts: How to I create a backup of my content ONLY?

texts:
I'm debating between using Feeds module and Backup and Migrate and I'm not sure which would be the best option here.

Here's the scenario - I've two versions of the same site - both drupal 7, both have the same content types and taxonomy structure. One is live, one is on a development server. Due to some unclear communication a bunch of content edits were added to the live site that need to be merged in to the development site where we've made major improvements with Views and several stylistic changes, so we can't just dump the database and then move it without wiping out all the new content on the live site.

So does anyone have a good idea on how to best move JUST the content tables from the database? I know it will be different from install to install, but if you could help me get an idea of what to look for I can use the backup and migrate module and just exclude every table except those which I need.

Thanks in advance.


texts: How to create and check block revisions?

texts: How to create and check block revisions ? I can see the option at bottom while creating a block but when I click to see the revisions the link doesn't work.


texts:
I am getting an error right after creating the tweet.libraries.yml file as per istructions given from a book about Drupal 8 theming. Can anyone help me fix this error?

  The website encountered an unexpected error. Please try again later.
  Error: Cannot use assign-op operators with overloaded objects nor string offsets in Drupal\Core\Asset\LibraryDiscoveryParser->buildByExtension() (line 138 of core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php).
  Drupal\Core\Asset\LibraryDiscoveryParser->buildByExtension('tweet') (Line: 87)
  Drupal\Core\Asset\LibraryDiscoveryCollector->getLibraryDefinitions('tweet') (Line: 66)
  Drupal\Core\Asset\LibraryDiscoveryCollector->resolveCacheMiss('tweet') (Line: 148)
  Drupal\Core\Cache\CacheCollector->get('tweet') (Line: 44)
  Drupal\Core\Asset\LibraryDiscovery->getLibrariesByExtension('tweet') (Line: 58)
  Drupal\Core\Asset\LibraryDiscovery->getLibraryByName('tweet', 'bootstrap') (Line: 54)
  Drupal\Core\Asset\LibraryDependencyResolver->doGetDependencies(Array) (Line: 31)
  Drupal\Core\Asset\LibraryDependencyResolver->getLibrariesWithDependencies(Array) (Line: 104)
  Drupal\Core\Asset\AssetResolver->getLibrariesToLoad(Object) (Line: 116)
  Drupal\Core\Asset\AssetResolver->getCssAssets(Object, ) (Line: 291)
  Drupal\Core\Render\HtmlResponseAttachmentsProcessor->processAssetLibraries(Object, Array) (Line: 161)
  Drupal\Core\Render\HtmlResponseAttachmentsProcessor->processAttachments(Object) (Line: 45)
  Drupal\Core\EventSubscriber\HtmlResponseSubscriber->onRespond(Object, 'kernel.response', Object) (Line: 111)
  Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.response', Object) (Line: 179)
  Symfony\Component\HttpKernel\HttpKernel->filterResponse(Object, Object, 1) (Line: 161)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
  Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
  Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 48)
  Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 98)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 77)
  Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
  Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628)
  Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

This is the content of the tweet.info.yml file.

    name: tweet
    type: theme
    description: 'A twitter Bootstrap starter theme'
    core: 8.x
    base theme: false

    libraries:
      - tweet/bootstrap

This is the content of the tweet.libraries.yml file.

    bootstrap:
      version: 3.3.6
      css:
        theme:
          css/bootstrap.min.css: {}
          css/bootstrap-theme.min.css: {}
      js:
        js/bootstrap.min.js
      dependencies:
        - core/jquery


texts: Detect profile2 save occasion in module and get user

texts:
Is it possible with custom module to detect occasion when user saves/updates his profile2 profile ? ( i know it is possible with rules but want to do it programatically in custom module).

And from that point, is it possible to load user data (the fields of profile2 profile) that just did the changes ?

Thanks for clues!


texts: Is it possible to subscribe to a newsletter without first having to register?

texts:
I am using the Simplenews module, but from what I've been able to conclude, is not possible to subscribe to a newsletter without first having to register.  Is that correct?

Is there a different newsletter module which will enable me to do this: offer a newsletter subscription to users without having to first become a registered user?


texts:
I want to create a custom voting module to learn how to write a module. The vote table will contain four fields (id, title, vote_up, vote_down).
Should I create a new table? If I create a new database table, how do I keep the relationship with the node being voted?


texts: Path to inline image  inside page.tpl.php to theme/images/ dir?

texts:
Simply  pasted to page.tpl.php doesn't work. It doesn't find the image and requires full path.

I know I've seen somewhere some PHP code which sets full path to image inside the theme's dir.


texts: How do I use Drush correctly to restore a site via the arr command?

texts:
I am having an issue with the Drush arr command working correctly.  I use drush to backup an archive on a testing server and then move it to a live server, or vice versa when needed.

Here is a typical command I use for restore

drush arr --db-url=mysql://name:pass@localhost/mydb

The database credentials on the test server are different from the live server.  When drush completes the restore process it does so correctly and then says "the database credentials are appended to the bottom of the settings.php file"

That's great, and it indeed appends the correct information about the database, but this never works.

drupal always tries to read the original database configuration that comes before the appended information.

So, I always have to open up an editor, open up the settings.php file, scroll down to the bottom, remove the appended information, then manually go back and change the config information.

This is a huge waste of time.

How do I use this command correctly to avoid that? I want to seamlessly be able to type the command and immediately start using the site without having to manually edit anything.

Also, given that the database config variable is an array, how do I just tell the settings.php file, via drush, to use one or the other? If I have config for a testing environment and a live environment, I simply want to tell it which one to use as needed.

EDIT:

I wanted to add some more information as to the errors I get as well as the settings.php information.

So, immediately after using the command above, this is the error I get on the server I am restoring to:

PDOException: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost'
(using password: YES) in lock_may_be_available() (line 167 of
/var/www/vhosts/domain.com/httpdocs/includes/lock.inc).

Here is what the settings.php file contains for the original db configuration:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'mptest',
      'username' => 'root',
      'password' => 'mypass',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Here is what is appended to the end of the settings.php file:

// Appended by drush archive-restore command.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'driver' => 'mysql',
      'username' => 'name',
      'password' => 'pass',
      'port' => '',
      'host' => 'localhost',
      'database' => 'livedb',
    ),
  ),
);

This looks to be the same except that the sequence for the config is different than the original.  Even so, I get the error as stated above. Could the config property sequence be causing this?


texts: Error accessing Views after copying site to another server

texts:
I inherited an out of date Drupal 8 site, and have been tasked with extracting some data for import into another location. I thought I would create a View to query the data that I'm after, and then work to export it.
When I navigate to http://localhost/admin/structure/views, I get the following error:
The website encountered an unexpected error. Please try again later.

Drupal\Core\Entity\EntityMalformedException: The &quot;view&quot; entity cannot have a URI as it does not have an ID in Drupal\Core\Entity\EntityBase-&gt;toUrl() (line 191 of core\lib\Drupal\Core\Entity\EntityBase.php).
Other pages that I have tested on the site load correctly.
I have migrated the site by copying the entire directory structure and the database to my local machine, updated settings.php to reflect the local database. I cleared caches and am able to log in and navigate to a large sample of pages successfully.
Some searching on this particular error doesn't seem to get me too far, except to some references of other modules (not Views).
Help?


texts: How do I use memcache in a custom block?

texts:
I have installed and configured memcache.
I have not got any single tutorial of memcache with custom block. I want to understand how memcache can be integrated with a custom block and views.


texts: How to add css depending on a field value?

texts:
I have a field attached to a node which contains an image or not.

If there is an image I should load a specific css(sass).

How can I do this?


texts: Submit handler in hook_form_alter not working in d8

texts:
I have hook_form_alter as follows :

function auto_ga_form_alter(&$form, &$form_state, $form_id) {
    global $base_url;
    if($form_id == 'node_p_request_form' || $form_id == 'node_p_request_edit_form' || $form_id == 'node_f_pro_request_form' ) {
      $form['#submit'][] = 'custom_form_submit_fn';
      $form['actions']['submit']['#submit'][] = 'custom_form_submit_fn';
   }
}

function custom_form_submit_fn(&$form, $form_state) {
  echo 'reached in submit handler';exit;
}

But its not going to the submit handler . both usage ( $form['#submit'][] OR  $form['actions']['submit']['#submit'][]) of submit handlers not working

And idea ??


texts: How can I change the order of vertical tabs?

texts: More specifically, I am using Location in Drupal 7 to allow people to add location to nodes, but I want it to appear at the top of the vertical tabs fieldgroup.


texts: How to sort a view on a Drupal Commerce product image field?

texts:
I have several Drupal Commerce views. I want to sort on whether the image is "interesting", which means not equal to no-image-available.png.

I have added "Indexed Commerce Product: Image » The image file." as a relationship but it's still not showing up in the sortable fields.

I remember there was something like "enforce" relationship but this is not showing up where I was expecting it:


texts: What are my options to rename a (huge) cache_form table which takes way to long?

texts:
I inherited a website that has cache_form more than 33Gb.

I've followed the following steps:

CREATE TABLE new_cache_form LIKE cache_form;

RENAME TABLE cache_form TO cache_form_backup;

And in other session:

RENAME TABLE new_cache_form TO cache_form;

Query is taking long long time and site is not responding.

What could the solutions be?


texts: Replace a specific integer value with a string?

texts:
I have a View that displays a list of all the content types, with price as one of the fields you can sort and filter by.

However, the client wants to have some items show up without a price, i.e something like "Price on demand" / negotiate.

Therefore I want to replace '0' value to show up as that text (translated for other languages), how would I best do this?

I use some exposed range filter in my view but couldn't see any extra functions to replace values of field items with strings etc.

I would need it changed in the View as well as the items' individual page (and generated PDF file, but that part I can do)

EDIT:
I have Better Exposed Filters, but after setting the replacement as:

0|Price on demand

It didn't seem to work or do anything. However my views uses a template, and I output the price by doing:

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

So I would first need to check if $content['field_price'] value is 0, then output my text string? Ideally I would prefer using some settings that can handle replacing the value for me.


texts: Views: How to change entity view mode settings when a contextual filter is available?

texts: I have a view it displays a few nodes in teaser mode. The view takes contextual filter and when filter is available I would like the content (node) to be displayed in full view mode. Is this possible?


texts: \Drupal::database()->select with Expression used as Condition

texts:
I am trying to execute this query:

'SELECT sd.entity_id AS entity_id, WEEK(node__field_start_date.field_start_date_value) AS week, YEAR(node__field_start_date.field_start_date_value) AS year
FROM
{node__field_start_date} sd
INNER JOIN {node__field_plane_reservation} pr ON sd.entity_id = pr.entity_id
WHERE (sd.bundle = :db_condition_placeholder_0) AND (pr.field_plane_reservation_target_id = :db_condition_placeholder_1) AND (week = :db_condition_placeholder_2) AND (year = :db_condition_placeholder_3)'

And I am using this piece of code:

    $database = \Drupal::database();
    $query = $database->select('node__field_start_date', 'sd')
  ->fields('sd', ['entity_id']);

    // Expressions
    $query->addExpression('WEEK(sd.field_start_date_value)', 'week');
    $query->addExpression('YEAR(sd.field_start_date_value)', 'year');

    // Conditions
    $query
  ->condition('sd.bundle', 'reservation', '=')
  ->condition('pr.field_plane_reservation_target_id', $refPlane, '=')
  ->condition('week', $weekNo, '=')
  ->condition('year', $weekYr, '=');

    // Join Tables
    $query->join('node__field_plane_reservation', 'pr', 'sd.entity_id = pr.entity_id');

And whenever I execute it, it give me the error:
Unknown Column 'week' in query or Unknown column 'year'.
How do I use a condition with a pseudo column created with an expression?


texts: custom module page -- i need it to use a predefined panels page layout

texts:
I've got this:

function foo_menu() {
    $items = array();
    $items['facadmin/directory'] = array(
        'title' => 'Faculty & Staff Directory',
        'page callback' => 'foo_facstaff_directory',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

Which then does this:

function foo_facstaff_directory() {
    $content = foo-make-html();
    $page = array();
    $page['#markup'] = $content;
    return $page;
}

I'd like this page to use a predefined panels template, but when I set 'facadmin/directory' as a selection rule, it doesn't do the smart thing automatically and just dumps the html into the content region -- no panels.

Help?!?


texts: What is the easiest way to install clean Drupal from scratch using drush?

texts: What is the easiest/quickest way to install clean Drupal from scratch on empty folder for testing purposes by using drush (without resorting to shell scripts or aliases).


texts: How to get View display label for field?

texts:
I'm trying to enable grouping for the Views Datasource module. I'm looping through the $rows array, which is where output is stored by the module before it's formatted into JSON. Problem is, the grouping field is stored in $options as its machine name, but $rows uses the user-defined label for field names. Basically, I just need a function to take the machine name for a field and return the display-set label for it.

I already tried field_views_field_label, but it returns an array of the labels for fields defined in the content type, where I need the label defined in the view display.

$group = $options["grouping"][0]["field"];
// Get grouping field as defined by the field options in the view display
$root = $options["root_object"];
$top_child = $options["top_child_object"];
if ($group) {
  $grouped = array();
    foreach ($rows[$root] as $key => $array) { // Values are numeric
      // Grab the grouping field value from inside the 3rd-level array.
      // Creating a label for grouping field will break everything
      $groupnode = $array[$top_child][$group];
      foreach ($array[$top_child] as $prop => $value) {
        if ($prop != $group) { // Ignore grouped field
          $grouped[$root][$groupnode][$prop][$key] = $value;
        }
      }
    }
  $rows = $grouped;
}


texts:
How can one change drupal's default CSS classes? They are set in drupal's core and I don't find if there is any hook to change the #attribute entry of a menu item.

CSS classes are already set before the theme_menu_link hook call, the classes of defined in menu.inc. Is there a hook to alter these values ?


texts: Drupal 7 aggregator module with BBC persian feed

texts:
I am trying to import the BBC persian feed from http://www.bbc.co.uk/persian/index.xml using the Aggregator module in Drupal 7. For some reason, I always get the same link for the article for all the imported items. I have tried with other RSS feeds form BBC.co.uk; only the Persian  one is not properly imported.

Is this a know issue? Is there a workaround? I presume it is a problem with the RSS parser in the module, and the Persian numerals, but I can't be sure.


texts: How to alter a form of content-type to prepopulate FieldCollection of EntityReference fields?

texts:
I have three content types :

Classroom (some fields)
Student (some fields and one EntityReference to Classroom)
KMDone (some fields and a FieldCollection)

KMDone is a content type which contains :
- a date
- a FieldCollection "kmdone_students"

The FieldCollection "kmdone_students" contains itself
- an EntityReference to the Student
- a distance "go" (Numeric fied)
- a distance "back" (Numeric fied)

Everything works fine except one point :

The generated form for the KMDone content-type requires to click several times on the "Add More" button to have enough rows for every student, choose one student on each select of each row, and then fill the form. Which is not confortable and can give some encoding errors due to user.

So, I would like to alter the form and prepopulate one "row" for each student.

It seems I have to work with the hook_form_alter hook, but how can I can I prepopulate one "row" in the FieldCollection (as if the user clicked on "Add more" button) for each EntityReference ?
To say it in other words : if the original form SelectBox have 17 students, I would like then to prepopulate 17 rows and set the EntityReference field for each student.

Many thanks in advance for your tips !

Kind regards,


texts: How do I programmatically create a new content type?

texts:
I'm building a module (my_module) in Drupal 7. It has some functionality and also
will create a new content type. In my_module.install, I implemented hook_install() (my_module_install()).

Can I use more hook_install() to create a new content type (my_module_install()) in this module?
If the answer is yes, how should I do this? Otherwise, should I do this in another module?


texts: Fetching node field values programmatically

texts:
I have figured out how to query the node table programmatically without using the deprecated db_query() function. However, I soon discovered that the actual content fields are not held in the node table, but in a separate revisions table.

I can't figure out how to select fields from the content nodes.

So for example, I can get a count of the number of nodes of type "entity", by using the following code.

use Drupal\Core\Database\Database;
$connection = Database::getConnection();

$sth = $connection->select('node', 'x')
->fields('x', array('nid', 'type'));

$executed = $sth->execute();
$results = $executed->fetchAll(\PDO::FETCH_OBJ);

$type_entities = array();

foreach ($results as $row) {

    // COUNT ONLY ENTITIES
    if ( $row->type == "entity" ) {
        $type_entities[] = $row->nid;
    }
}
echo "Total: ".count( $type_entities );

This code works fine, because I am not referencing any data from the node, just counting the node id's.

But say I also have a field entitled "color", and I want to return that field too, so I can count the number or red, green, blue, etc? The following code won't work, because the "color" field is not in the node table, so can someone please help me to create a working version of the following:

use Drupal\Core\Database\Database;
$connection = Database::getConnection();

$sth = $connection->select('node', 'x')
->fields('x', array('nid', ['type', 'color'] ));  // <-- ADDED color FIELD

$executed = $sth->execute();
$results = $executed->fetchAll(\PDO::FETCH_OBJ);

$type_entities = array();
$is_red = array();
$is_greed = array();
$is_blue = array();

foreach ($results as $row) {

    // COUNT ONLY ENTITIES
    if ( $row->type == "entity" ) {
        $type_entities[] = $row->nid;

        // COUNT COLOURS
        if ( $row->color == "red" ) {
            $is_red[] = $row->nid;
        } else if ( $row->color == "green" ) {
            $is_green[] = $row->nid;
        } else if ( $row->color == "blue" ) {
            $is_blue[] = $row->nid;
        }
    }
}
echo "Total: ".count( $type_entities );
echo "Red: ".count( $is_red );
echo "Green: ".count( $is_green );
echo "Blue: ".count( $is_blue );

So how do I do that, only fetching the "color" field properly using ->fetchField() or ->fetchCol() maybe?

Thanks for looking!


texts: Execute cron job automatically after a specific interval of time in windows

texts:
I've created a custom module in drupal and implemented hook_cron. My hook is working perfectly, when I click on run cron button from admin interface.

How can I automatically execute my hook after a specific time interval is passed,  without clicking on the Run cron button from the administrative interface?


texts:
I am creating a view which shows nodes of content type Movies. Movie content type has fields name, description,rating, and release date. Fields the view displays are name ,description and release date. What I want to display those nodes only that have release date set to some future value.
I googled a lot but did not find anything. How to do it?


texts:
I need to run a hook after a drush command in another module has been run to clean up a file on the server, and so based on what I've read here and here I'm trying to implement a post command hook on the node-export-import command.  In mymodule.drush.inc I have a function defined as

function drush_mymodule_post_node_export_import(){
  // Do my magic here
}

but it isn't called at all after running the node-export-import command.  I've played around with other naming variations, but none are getting called.  My module is enabled, and I've cleared cache.  I'm using version 5.9.  Is there something I'm missing?

Thanks.


texts:
I want to find out whether a physical file is managed by Drupal and if it is, then load it.

I'm having trouble with the documentation which keeps displaying "File not found" at crucial moments, but it seemed that this ought to work:

$query = \Drupal::entityQuery('file');
$query->condition('uri', $file_uri);
$entity_ids = $query->execute();
if (count($entity_ids) == 1) {
    $file = \Drupal::entityLoad($entity_ids[0]);
}

However, I get this message: PHP Fatal error:  Call to undefined method Drupal::entityLoad()


texts: How do I pass parameters as JSON format to the HTTP client request?

texts:
How can I pass parameters to the http client get request in json format:

$clientFactory = \Drupal::service('http_client_factory');
$client = $clientFactory->fromOptions(['verify' => FALSE]);

$params = '{"data1":"",
"data2":"mydata"
"data3":"mydata",
"data3":"mydata",
"data5":"mydata"}';

$url = 'https://myendpointurl';
try {
  $response = $client->get($url, array(
      'headers' => array('Accept' => 'text/plain'),
    )
  );
  $data = json_decode($response->getBody());
}
catch (RequestException $e) {
  watchdog_exception('my_module', $e->getMessage());
}

Where I need to put $params variable in my code?


texts: Drupal 7 user register form in overlay on page load

texts:
One of my requirements is to show the user registration form in an overlay kind of interface.

From the Examples module issue queue, comment #14 http://drupal.org/node/930058 I found a module, learned the hook_admin_paths() and hook_admin_paths_alter(). I installed that module in my local test site. Added "user/register" path to $paths of hook_admin_paths() and granted permissions to use overlay. It works pretty much as expected with the click event however my requirement is to trigger the overlay for onpageload event.

I tried calling a js script which would trigger click event from hook_overlay_parent_initialize() and module's info file by settings scripts[] = myoverlay.js.

The js script looks as below,

(function ($) {

Drupal.behaviors.loginLoad = {
  attach: function (context, settings) {
    alert("trigger client event"); // works
    $(".menu-589 a").attr("title", "click"); // works
    $(".menu-589 a").trigger("click");
    // This one didn't work. Tried triggerHandler() and click() as well.
  }
};

})(jQuery);

My jQuery expertise is very limited. I'm trying to figure out how the overlay fires for onclick event.

From what I learned the paths to be opens in overlay are defined in Drupal.settings.overlay.paths.admin. And overlay-parent.js and jQuery BBQ does some tricks to show things in modal window.

Any help to figure out this will be appreciated.

On a side note : For Drupal 6 projects I have used modal frame api module often with onclick event. This module doesn't seems to be available for Drupal 7 and it is going to be deprecated in favor of overlay in core. Is overlay an API module ?  It doesn't appear to be the case from my experience.


texts:
How to export users with passwords?
The Users export module cannot help, it export without passwords.


texts: How do I add a post cost to the checkout page?

texts:
I want to add a fixed post cost to the checkout page in ubercart 2(drupal6). How do I add it?

Currently I have this.

Order total preview:
Subtotal:       1000
Order total:    1000

I want this.

Order total preview:
Subtotal:       1000
Post cost:       400
Order total:    1400


texts: Commerce PayPal wps sends to and gets data from sandbox but no payment method available

texts:
I'm on localhost without ssl and fix IP.
I can checkout with PayPal WPS, go to sandbox, confirm as buyer, and when I click in the sandbox I go back to my testsite after confirming to leave SSL.

In my logs I can see (watchdog) that the function commerce_paypal_wps_redirect_form_validate() works fine and gives me a lot of data from my client and the transaction.

In my sandbox seller account I can see the payment is accepted and I earned my bucks ;)

Here the problems:

The orders overview at admin/commerce/orders only shows pending orders instead completed although the posted data from paypal show

  [payment_status] => Completed

Next when I go to the payment of any order I see that there's no payment method available although payment is done per WPS.

admin/commerce/orders/1/payment:

  No payment methods available to add payments.

I believe that these are the reasons why my hook I want to use is not called??
I want to change the user role after the transaction is completed so I took hook_commerce_paypal_ipn_process() without success.

Does anybody has any ideas??

My modules: commerce 7.x-1.11+52-dev, PayPal 7.x-2.3+4-dev, Commerce (Tax)7.x-1.0-rc2, rules 7.x-2.9


texts: Earliest point in page load to issue a redirect?

texts: I'd like to redirect all of the paths for my media entities the path of a file on the entity. What hook would allow me to do this as early in the page load process as possible?


texts: How to make a competition input form and a view?

texts:
I want to put scores in a form. See screenprint:

Some details about it:

2 pulldown menu's with players.
2 text boxes for the score, example: (8) and (2).

In the above example, the automatically calculated "comp score" will be 3 and 1. If however the score is (6) and (6), then the comp score will be 1,5 and 1,5.

So to summarize (about how to calculate the "comp score":

When the score is equal both players get 1,5.
The winner gets 3, the loser gets 1.

They play in poules, several matches. Each match is put in like in the screenprint above.

The scores will be added up. And in a view they will be shown on the site as a ranking. The best on top.

I don't know how to imput the data, automatically give the comp score and how to add them up (to make the view will go).


texts: Mathjax module does not render on edit ckeditor

texts:
I have installed mathjax module and ckeditor module, but when I try to insert math code using math button on ckeditor, the math codes does not rendered correctely, math code become hidden. Math code rendered successly after content is submited.

is there anyone can help me to fix?

here my screenshot


texts: Filter by field that only exists for some content types shown in view

texts:
We're trying to create a view with a number of exposed filters in D7. There are a number of different content types that we want to show in the same view, and to filter using the same filters. However, most but not not all of the content types have all the fields we want to filter by.

For instance, "Difficulty Level" is a field common to many of our content types, including Tutorial and Project. However, an Idea does not have this field.

Ideally, we would like to let end-users filter by a number of fields and specify whether they want the filter to be strict or flexible. Let's say the user is looking for resources that have a Difficulty Level of "Beginner" or "Intermediate":

strict would mean that only nodes that fully satisfy the filters are shown:

no Ideas would be shown, because Ideas by definition don't have a Difficulty Level field to begin with
Tutorials with a Difficulty Level of null would also not show up
an Advanced Tutorial would not be shown

flexible would mean that all nodes that don't outright disagree with the filters are shown:

all Ideas would be shown
Tutorials with a Difficulty Level of null would be shown
an Advanced Tutorial would still not be shown

Is this doable with Drupal? I've searched high and low and haven't been able to find anyone with such a problem...

EDIT: Using the and/or groups is one possible solution, however it doesn't work for taxonomy fields: these lead to joins instead of left joins, so that you can either get the items that have the requested keyword or the items that don't have any keywords, but not both at the same time.


texts: Custom entity field validation using constraint

texts:
I have custom entity (component) with two fields field_area_type and field_dd_test_data. I want to add custom validation to make sure that user must enter either of two fields. I have used ConstraintValidator as suggested in different blogs.
https://www.drupalwatchdog.com/volume-5/issue-2/introducing-drupal-8s-en...

I am able to validate for one field, means in validate function I get only value of one field. How can I get values of both field in validate function of ConstraintValidator? Please help me


texts: PHPUnit errors occur when running drupal-check

texts:
I am trying to run drupal-check on the social_auth_dropbox module (vendor/bin/drupal-check -ad web/modules/contrib/social_auth_dropbox) and I'm facing this error:

Warning: Class 'PHPUnit\Framework\MockObject\Matcher\InvokedRecorder' not found in /Users/Documents/sample/my_site_name_dir/web/core/tests/bootstrap.php on line 197
0/11 [░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 0%
Fatal error: Declaration of Drupal\Tests\BrowserTestBase::setUp() must be compatible with PHPUnit\Framework\TestCase::setUp(): void in /Users/Documents/sample/my_site_name_dir/web/core/tests/Drupal/Tests/BrowserTestBase.php on line 39


texts:
I am porting a module to Drupal 7. The module has hook_update_N() functions called from hook_install(). There are some insert queries made inside one of the hook_update_N() functions. But my hook_update_N function is not running. Is there any way to explicitly invoke hook_update_N functions?

I know my question is almost same as this How to get hook_install() to run all hook_update_N()?. But I don't understand how hook_update_N() is called. I have run updates in my Drupal site which I think also run updates of custom modules but it seems hook_update_N() is not getting triggered. Because, I have added error_log() function inside hook_update_N() but the log file is empty.


texts:
After a recent migration from D6 to D7 some of the product descriptions made in the body of certain content types contains technical data like this:

[0...+70°C: ±0,2°C]

This is interpreted as tokens by the site and I get this message when I try to edit the content and then save the changes:

The Body is using the following invalid tokens: [0...+70°C: ±0,2°C]

How can I get around this, since it is not possible to save changes? I have tried to change the value directly in the database and then clear all cache, but the problem is still the same.

What to do?


texts:
I have created a webform block. After I enter all the info in the webform, I clicked the Submit button. Nothing happens. Do you know why the Submmit button is not working?

This webform block's submit button works: http://godrupal.info/?q=contact-us

Actual webform node's submit button works : http://godrupal.info/?q=node/16. Then I created block of the node/16 but then this webform blocks's submit button does not work: http://godrupal.info/?q=plan-an-event


texts: Can I configure Send by Email to use CC instead of BCC?

texts:
So I have a node that is using the Print Module (www.drupal.org/project/print) and it's associated send by email functionality.

The issue is that if I include multiple emails on the send by email page, it sends them so that the email addressees cannot see the other people it was emailed to.

For instance, if my send to looks like: example1@example.com, example2@example.com

Both example1 and example2 will receive the email, but with only their name in the To: line.  Is there a way to get the rest of them to show up there as well, or in the CC: line?

Thanks.

Here's the portion of the code I was able to find where it splits it into multiple emails:

  $addresses = explode(', ', $form_state['values']['txt_to_addrs']);
  foreach ($addresses as $to) {
    if ($use_job_queue) {
      // Use job queue to send mails during cron runs
      $queue->createItem(array('module' => 'print_mail', 'key' => $print_mail_send_option_default, 'to' => $to, 'language' => language_default(), 'params' => $params, 'from' => $from));
    }
    else {
      // Send mail immediately using Drupal's mail handler
      $ret = drupal_mail('print_mail', $print_mail_send_option_default, $to, language_default(), $params, $from);
    }
    if ($use_job_queue || $ret['result']) {
      flood_register_event('print_mail');
      $ok = TRUE;
    }
  }

Anyone know how I can make that so it just sends one email to all of the addresses?


texts: How do I invoke token substitution with Pet?

texts:
I have to send some emails in a custom Drupal 7 module.

I'd like to use the PET module (Previewable email templates) to manage the templates and drupal_mail() to send emails because it already uses SwiftMailer to send emails.
The problem is that the body of the email I get from Pet has some tokens that I should replace before the email is sent.

How can I replace them?

This is the code I'm using.

$pet = pet_load('test1');

$params['format']= "text/html";
$params['charset']= "UTF-8";
$params['email_subject']= $pet->subject;
$params['email_body']=$pet->mail_body;

///$params['email_body']= <body with token replaced>

drupal_mail('myLib', 'customNotifications', 'xxx@gmail.com', language_default(), $params);


texts: How does one add a Total(s) row to Views results?

texts:
After doing some research, it seems like the best way to get a Total(s) row added to a Views table is via the Views Aggregator Plus module. (Is there an easier/better way?)
As can be seen below, I'm trying to list a bunch of nodes grouped by the first column (the taxonomy term "Type"), with the second column containing the number of each.

I'd like to add an additional row to the bottom:

Total | 6

...but no matter what I try, the additional row doesn't show up in spite of what the module documentation, various videos, and blog posts are telling me.
In the view Format, I'm using "Table with aggregation options", and the settings are as can be seen here:

Under Column Aggregation, I should be able to check "Apply column function" and select Sum (I think), but this has no effect on the live preview.  I tried this on both fields (and even both together), and it made no difference.
I'd like to make the Total row part of the table, rather than a hacky solution where I calculate it in the view header or footer.  How can this be done?  What am I missing?


texts: D7: Add a class to a list item when the created date is less than 14 days old

texts:
Using Drupal 7 and Views, I currently have a view that produces a list of 5 teasers of the content type "News." 5 teasers is a hard rule. I'd like to conditionally format the rows so that when their "created date" is less than 14 days old so that I may styles them as "New" with CSS styles. So if there are 3 "New" rows, the balance are 2 unmarked rows.
How to do so?
Update
I had the idea of using the "time ago" date format to populate the class name. However, the format for "time ago" changes. Unfortunately, I can't set the granularity to "days" which would have allowed me to add the text as a class, i.e., date1 through date24 for the past 2 weeks.
Update #2
My genesis subtheme is ignoring any preprocessor routines, see more here. However, I can add the routine to my base template.php.
Update #3
Thanks to Елин Й. for the working code:
function genesis_preprocess_views_view_list(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'recent_news_widget') {
    foreach ($view->result as $key => $result) {
      if (time() - strtotime($result->node_created_day) < 14 * 24 * 60 * 60) {
        $variables['classes'][$key][] = 'new';
        $variables['classes_array'][$key] = isset($variables['classes'][$key]) ? implode(' ', $variables['classes'][$key]) : '';
      }
    }
  }
}

In an offline discussion, Елин Й. explains why this works; "I took a look in the views theme.inc and found out that, the classes array is flattened to another variable called 'classes_array' you need to do it as well in order to get your new class also added in this array.


texts: figuring out menu token path for file field

texts:
I'm trying to use menu token and file (field) path to get a path to display a node's PDF field from a menu link.

I tried with the tokens:

[node:field_pdf]/[file:url]

with and without relative path before, and there seems to be a bug that prevents me from saving it when I change the path.

Still can't figure what my path should be..

any help, or advice for the best way to go about it, will be most appreciated.

thanks in advance


texts:
I want to display the users emails with views, but it doesn't show for the users, only the administrators can see them.

How can i display them to the users with views, and i have a warning: Email address for a given user. This field is normally not shown to users, so be cautious when using it.


texts: How to import Term reference (autocomplete term widget) inside field collection with Feeds & feeds tamper

texts:
I would like to be able to import content from CSV using Feed.
My content type are like this :
-Titre

-Field Collection :

--Name (simple text)

--Term (Term reference of type Autocomplete term widget (tagging)

For begin able to import field collection i have applied the #16 patch https://drupal.org/node/1063434#comment-5217400

Everything is working fine exept the insert of my Term field in my fieldcollection because is it of type Autocomplete term widget and if its a new term.
I want to keep this type of widget because i want to be able to create new term if they doesnt exist already.
I confirm that if i enter a existing term value for my Term field in my csv, my term is succesfuly added.

I am using :

Feeds : 7.x-2.0-alpha8+7-dev

Feeds Tamper : 7.x-1.0-beta3+56-dev

Field collection : 7.x-1.0-beta5

I dont know what i have missed... i am lost and blocked on this bug since 2 weeks.

I hope someone will help me,

Best regards

Jérôme


texts:
In Drupal 7 I'm facing one problem, I'm going to implement a comment system in that way that it should work as chatting systems. I've a content type Article, at the end there is a comment box where users can leave comments.

If I add a comment to the article it should be showed in every user's browser if they are viewing it, and at the same time they can debate/talk about that article without refreshing the page.

It will be real time commenting.


texts:
Is it possible that node translations aren't new nodes? For example if I translate /node/1 I get /node/2 and this is problematic in some cases (comments are not shared between #1 and #2, and entity references are not reused).

Detailed walkthrough:

I'm using locale, translation, variable and i18n. I've got 2 languages configured: EN, FR. I have content types News and Event. Both have Multilingual support: "Enabled, with translations". The News has fields:

title
body
reference to a Event (implemented with entityreference)

I create 2 node instances:

/node/1 (#1) Event (EN)
/node/2 (#2) News (EN) with reference back to #1

I edit #1 and add a translation (FR) and #3 is created. I then translate #2 and #4 is created. The problem is that I have to respecify that the reference from #4 is #3 and not #1. If I use the "Synchronize translations" feature of the content type the workflow is a bit better but still not exactly what I want since on the FR front end when viewing #4 the reference to #1 will be displayed in EN and not FR.

Is there any way to have translations not creating new nodes but instead just translating some fields only?

Also, is the module i18n the "defacto standard" for implementing multilingual sites in Drual 7? Or is there something better out there?


texts: How do I create relevant keyword search?

texts:
I created a view and fetched the content from a content type. I created an exposed filter with two fields (title and body) using contextual filters.
Search works for exact match keywords, but it doesn't work with similar keywords. For example, for timesheet and application it works fine, but if I search using the wrong spelling (for example, timeshet or appliction), it doesn't work.
How do I create a keyword relevant search?


texts: Disable price field when checkbox is checked (node add form)

texts:
I would like to disable 2 price fields when a checkbox is checked. This could be easier with webform by I want to implement that on the node add form (admin).

Thank you in advance.


texts: Is it possible to apply FAPI #states to profile2 fields on the user registration form?

texts:
I have a profile embedded into the user registration form and am trying to add a conditional to one of the fields in order to show/hide related fields.

The fields are all part of the same fieldgroup in the following layout:

username
email

profile (fieldset)
 - About you (fieldset)
  - fields

submit button

I think the issue is how to actually target the fields and apply #states to them.  Any ideas? I tried digging through Devel Themer, but couldn't get anywhere with it.


texts: How can i add multiple instances of newsletter subscriptions?

texts:
I want to display newsletter subscribe in different pages, in different ways. Hence once I have set newsletter : subscribe to home page, it does not apply to other page by default.

How can I can assign it to different pages in different positions?


texts:
I have a content type with an Entity Reference field. The field references multiple images.

Using Display Suite, I can set the display format to "entity id" and when I view the content, I get a list of IDs as expected. But when I change it to "Rendered Entity", I'd expect the rendered images, but nothing is actually rendered. This is not a CSS-issue, the rendered field has no actual HTML in it. Any ideas?


texts:
Can't figure out why the following query executes directly through phpMyAdmin perfectly well:

SELECT id FROM `stats` WHERE type="load" ORDER BY id DESC LIMIT 1

but firing this:

db_query('SELECT id FROM {stats} WHERE type = '.$param.' ORDER BY id DESC LIMIT 1')->fetchField();

from a module outputs:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'load' in 'where clause': SELECT id FROM {server_stats} WHERE type = load5 ORDER BY id DESC LIMIT 1; Array ( ) in server_tab_stats_submit() (line 750 of /home/dev/public_html/sites/all/modules/custom/server/server.inc).

Column's name there is "type", I don't know why Drupal query thinks "load" is a column, it is just a value derived from $param variable.


texts: What does a basic module look like that includes a content type, a couple of fields and a view?

texts: I am looking at turning my Features into proper modules. There is nothing fancy to them other than a content type, a couple of textfields attached and a view. It looks like the features module pretty much exports these into a module anyways but it looks like it relies on some helper functions in the features module to get this going. How can I convert my feature so that it doe not require the features module to be installed?


texts: autocomplete taxonomy field depend on another taxonomy field

texts: There is a content type Animal in which two taxonomy field are used  say Animal Type and Breeds . Breeds taxonomy is autocomplete taxonomy field . so What i want Breeds taxonomy field  depend on Animal type taxonomy field. i.e, when cats are select from animal type field then breeds taxonomy show only cats type breeds .How can this acheive ?


texts: How to emulate all the AJAX functionality when the form is rendered after an AJAX callback?

texts:
I have a Drupal form, but I am adding it to the page as the result of an AJAX callback.

I need this form to trigger a new callback. My code below:

      $form['#suffix'] = '
this is the return box
';
  $form['#attached']['js'] = array('misc/ajax.js');

  $form['markup'] = array(
    '#type' => 'markup',
    '#markup' => '
This is a form
'
  );

  $form['button'] = array(
    '#type' => 'button',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'module_myform_callback',
      'wrapper' => 'form-return-message-box',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $replace_layer = '#somelayer';

  $commands = array();
  $commands[] = ajax_command_replace($replace_layer, drupal_render($form));
  $page = array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );

  ajax_deliver($page);

So this is what happens: this form is being added into a container called 'somelayer' that already exists on the page (I didn't add that part of the code because I thought it would be unnecessary). It was called from a link with the class 'use-ajax'.

So the form renders on the page as desired after an AJAX callback triggered by the link.  This part works allright.

But here is the (very) tricky part: I would also like to preserve the new form AJAX functionality (check the '#ajax' part of the array), which doesn't occur. After the form is rendered, the button won't trigger any AJAX code. By clicking on it, the page will refresh, not triggering the callback function (not added here to preserve space).

By looking into source code of a regular form page with AJAX, you will see code like this that enables the AJAX functionality:

"ajax":{"edit-something":{"callback":"module_formname_callback","wrapper":"wrapper-name","method":"replaceWith","effect":"fade","event":"change","url":"\/spabear\/system\/ajax" ...

By looking at the source code of the form added into my page, I can see there is no piece of  code that would trigger the AJAX callback in my dynamically loaded form. How can I emulate all the AJAX functionality when the form is rendered after an AJAX callback?


texts:
I am really new to Drupal, so this is a beginners question.
I need to create a website with a dropdown within the header, where visitors can choose a region (not a language, just a region, like "Europe", "US", ...). The entire page should be filtered according to this selection, so if the visitor chose "US", some parts of the navigation or parts of the content should not be visible.

Is this possible with drupal?

And, more importantly: how would you go about this? The only thing I could think of is create a taxonomy for each "region" and assign content items and navigation items. Is that a good idea? Is there a better way to go?

I'd be thankful for any suggestion. Thank you.


texts:
I'm using drush to make version updates and any time a module (in todays case, recaptcha) needs to be updated, it successfully does the update.  However it seems to reset the database turning off every single non-core drupal module.

I cant find anything about this on the internet anywhere. Anyone have any ideas?


texts: Add values from feed into the users database table

texts:
I am new in Drupal. I am currently building a stand alone website (non Drupal website) but want people to register through the custom form and all the users data to go into the Drupal's database.

So the admin can manage the users through Drupal admin.

I am initially thinking to use a custom form so users can insert the information and then store all the values in JSON file and then install a module in Drupal to get the JSON's information and then store them into the Drupal user's table.

I will really appreciate your support and suggestions.

Thanks.


texts: Trying to make gallery with views in Drupal 7

texts: I have made 2 content types one is called Series and the other is Pictures. I have made a field on Pictures that will reference to Series. Using views I made a tab menu page that will appear on only the Series content type. What I'm having trouble is having to show all the Pictures that is referenced to that series. How would I do this?


texts: Displaying fields from my content types in a module

texts:
I am learning how to write modules at the moment. The following piece of code simply pulls out of the database some data and selects just the nid, title and created fields

function photo_gallery_contents($display){

$max_num = variable_get('photo_gallery_max', 3);

$query = db_select('node', 'n')
->fields('n', array('nid', 'title', 'created'))
->condition('status', 1) //Published.
->condition('type','portfolio') // Only want our photos aka Portfolio content type
->orderBy('created', 'DESC'); //Most recent first.

if ($display == 'block') {
// Restrict the range if called with 'block' argument
$query->range(0, $max_num);
} // Now proceeds to execute().
// If called by pge, query proceeds directly to execute()

return $query->execute();

}

This works fine but how do I access the other fields I created for my "portfolio" content type such as "field_image" or "field_category" both of which I added? I just cannot work out how to do this. Your help will be so appreciated!

I've written other hooks that represent this information on the page or block, at the moment I am showing a list of links to my nodes. I want them to be images with links instead:

function _photo_gallery_page() {
$result = photo_gallery_contents('page');
//Array to contain items for the page to render.
$items = array();
//Iterate over the resultset and format as links.
foreach ($result as $node) {
  $items[] = array(
  'data' => l($node->title, 'node/' . $node->nid),
  );
}

if (empty($items)) { //No content in the last 2 weeks.
  $page_array['photo_gallery_arguments'] = array(
    //Title serves as page subtitle
    '#title' => t('All photos from ever'),
    '#markup' => t('No photos available.'),
  );
  return $page_array;
}

 else {
  $page_array['photo_gallery_arguments'] = array(
    '#title' => t('All photos from ever'),
    '#items' => $items,
    //Theme hook with suggestion.
    '#theme' => 'item_list__photo_gallery',
  );
  return $page_array;
}

}

So how do I swap $node->title to show the image instead?


texts: Custom fields in User registration, how to save?

texts:
I thought that I needed to, in my submit handler function, call user_save() to save my user profile data.  But when I call user_save I get duplicate entry errors because it appears user_save is being called twice.

here's a snippet of code:

function all_data_form_submit($form, &$form_state) {

  $fname = $form_state['values']['field_first_name']['und'][0]['value'];
  $lname = $form_state['values']['field_last_name']['und'][0]['value'];

$edit = array(
  'name' => $form_state['values']['name'],
  'pass' => user_password(),
  'mail' => $form_state['values']['mail'],
  'init' => $form_state['values']['init'],
  'status' => 0,
  'access' => REQUEST_TIME,
    'field_first_name' => array(LANGUAGE_NONE => array(array('value' =>
$form_state['values']['field_first_name']))),

);

user_save(drupal_anonymous_user(), $edit);
<snipped>


texts: How do I set the absolute path for an image?

texts:
I use image upload default ckeditor and IMCE module for drupal 8. But both of them return relative paths.

Output code actual relative path:

Output code expected absolute path:

How to correct it?


texts: Block is not showing up in a custom taxonomy page template

texts:
I am using Drupal 7
I have a content type courses. I have a page folder in template folder, with courses.tpl.php file. When i go to courses page it is showing contents from courses.tpl.php. Issues is that courses.tpl.php is not rendering blocks.

I checked region in info file. I cleared cache etc, but block is not rendering.
I am not sure, if this page is a taxonomy page. 'footer_testimonials' is the block i am trying to render in this page, but it is not showing up.

'footer_testimonials' is showing up in page.tpl.php but not in courses.tpl.php

    <?php print drupal_render(drupal_get_form('course_searchbox'));?>

<?php print $page['page']['course_page_top_ad']['block_1']['#markup'];?>

Popular Courses: Certificate IV in Bookkeeping, Diploma of Accounting, Diploma of Business, Advanced Diploma of Accounting

Courses

    Central College Distance Education offers a range of Government and Industry Accredited courses ready to help launch your career.  Remember, Central College has been launching careers for over 30 years.  You may also be interested in our specialty Central College Certificates that will help you better manage your existing business and do it in your own time at your own pace, right in the comfort of your home.

<?php
//$taxoTerm = course::get_taxonomy_term(1);
$categories = course::getAllCategories();

foreach($categories as $category):?>

<?php echo $category->name;?> Courses

            <?php //get courses by taxonomy
                $courses_term = course::courses_by_term($category->tid);
                $i = 0;
                foreach($courses_term as $course):
                $courseObj = course::getCourseByNid($course->nid);
                    $i++;
                ?>

<a href="<?php echo course::courseUrl_alias($course->nid);;?>"><?php echo $courseObj->title;?>

                <?php endforeach;?>

<?php
if($i%2==0):
    echo '

';
endif;

endforeach;
?>

Testimonials

<?php print render($page['footer_testimonials']);?>


texts: Is there a simple way to alter core node/add/my_node_type to adding/my_node_type?

texts:
I don't want to show "node/add" in my url "node/add/my_node_type", instead I want to have "adding/my_node_type". Is there a simple way to hide "node/add" but not loose those args?
I want to have "node/add/my_node_type" functionality after hitting "adding/my_node_type".

I can't see form add or form edit patterns in path so I think it is not so easy...

Of course after that I will need "node/%/edit" to be "editing/%"...


texts: Persistent variable (`variable_set()`) name restrictions

texts:
Are there any restrictions, conventions, etc. for the names of persistent variables created with variable_set()?

Aside from project name prefix, I haven't found anything in the documentation. However, I notice that most modules restrict themselves to the same rules that apply to PHP variables.


texts: AJAX - How to dynamically add options to select?

texts:
In my drupal module, I want to dynamically add values to my select list. I also write them to the database. After it is added to the select and written to the db, I sort the options of the list alphabetically.

No problem at all, but whenever I add a value that will be the last one in the list (say zebra), and I select it right away, I get an "illegal choice detected" error. Why is this and how do I fix it?

Code when creating my form:

   $form['acategory_text'] = array(
      '#type' => 'textfield',
      '#title' => t('Nieuwe categorie'),
      '#size' => 25,
      '#maxlength' => 31,
      '#attributes' => array(
        'class' => array('textfield'),
      ),
    );

$form['acategory_button'] = array(
  '#type' => 'button',
  '#value' => t('+'),
  '#ajax' => array(
    'callback' => 'new_acategory_callback',
    'wrapper' => 'orderapp',
    'method' => 'replace',
  ),
  '#attributes' => array(
    'class' => array('button'),
  ),
);

$form['store_appcategories'] = array(
  '#type' => 'select',
  '#default_value' => '',
  '#title' => 'Order.app categorieën',
  '#multiple' => TRUE,
  '#options' => get_values('ac_id','appcategory',appcategories_load_multiple(FALSE, array('sid'=>$id))),
  '#prefix' => '
',
  '#suffix' => '
',
  '#size' => 7,
  '#ajax' => array(
    'callback' => 'get_mapped_categories_callback',
    'wrapper' => 'orderapp',
    'method' => 'replace',
  ),
);

Callback method:

function new_acategory_callback($form, &$form_state) {
  $newappcat = $form_state['values']['acategory_text'];

  $id = $form_state['values']['id'];
  $entity = entity_create('appcategories', array('sid' => $form_state['values']['id'], 'appcategory' => $newappcat));
  entity_save('entity_test', $entity);

  $form['store_appcategories']['#options'][] = $newappcat;

  usort($form['store_appcategories']['#options'],create_function('$a,$b','return strcasecmp($a,$b);'));

  $form_state['rebuild'] = TRUE;
  return $form;
}


texts: how can i remove the login form from the home page

texts:
I'm trying to remove the login form from the front page, but i see both frontpage and user/login page are using the same template file: page--front.html.twig.

Is there a way to use two different template files for each page?


texts: Import users into Drupal with data from a CSV file

texts:
How can I import users fom a CSV file in Drupal 8?

I’ve found this module but it is not updated for Drupal 8:

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

I think that I can make an import directly with a MySQL script but is it possible with Drupal (I know I can insert datas directly into database but I don't know if Drupal system will allow that method)?

I’ve found this question but it is not exactly what i need :
Importing a bunch of users from csv spreadsheet file into Drupal 8

I import data from a csv file and it is not a migration from a drupal site.


texts: how to add #states property to a field element in drupal 7?

texts:
I wanted to add #states property to a select list field in cck input form created by content type. I ve tried the following code but the states property is not set to the field. Can anyone suggest on how to do it.

$form['field_ctype']['und']['#ajax']=array('callback' =>'_ajax_menu_check_boxes',
                                              'wrapper' =>'edit-field-sub-menu',
                                            'effect' => 'fade',
                                            'event' => 'change',
                                            );
$form['field_sub_menu']['und']['#states']=array(
                                  'visible' => array(
                                 ':input[name="field_ctype"]' => array('value' => '2')));

could anyone suggest me where I am going wrong. Is it possible to add ajax property ans states property to a same field?

Note : The Ajax property for the field_ctype works fine. Only the states property is not working.


texts: List content types using views in Drupal6 (Views 2)

texts:
Is it possible to generate a list of all the content types in use using Views?
I would also like to restrict the content types that are listed.
I want to get the machine-readable-name of each content type and will then use the 'Views Custom Field' module or something to expand on each item.


texts: Save Ubercart order in database, processed through custom payment gateway

texts:
I am developing a custom payment gateway module for ubercart, I am able to complete an order on the third party payment system using their api and its working fine, the problem I am facing is how to save that completed order in the database. If we will see in paypal payment gateway for ubercart when we complete an order, Under store option we have an option to view the orders and there status (please check screenshot below), this is the same thing I want to achieve, in-short how can I keep track of orders processed through a custom payment gateway.

I know there is a hook uc_order_save($order) in ubercart, but I am confused how to implement it, so that it can interact with the internal values of ubercart orders. I am sure there will be a way in ubercart to achieve it.


texts: Drupal not using #weight when inserting form elements with form_alter

texts:
I'm inserting an Ajax element into the node_add form, but it always goes to the end, even though the weights are set in the order I want them to be.  It feels reminiscent of this issue from D7:

https://www.drupal.org/node/893392

...But form['#info'] doesn't seem to exist anymore.  What, in D8, could be preventing the form from rendering the form elements in order of ascending weight?


texts:
I need to remove jquery.ui.theme.css file, for this in my template.php I implement the below mentioned code:

function GNG_css_alter(&$css)
{
unset($css[drupal_get_path('module', 'misc') . '/ui/jquery.ui.theme.css']);
}

but its not working.


texts:
I have a view block that shows a sub-set of nodes. In the configuration page, the autopreview section shows content, so I know the filters for the view are set up correctly. I configured the block to show on only the listed pages and entered <front> for the page.  Unfortunately, the front page shows only the following content and a static block.

  No front page content has been created yet.
  •Add new content

The weird part is that this static block is configured the same way the view is configured  to show only on the front page.

Why doesn't the view block appear on the front page?


texts: How to hide all nodes of a particular content type?

texts:
I have a site that used to run polls, but has stopped doing so.  I'd like to keep the poll nodes in the database, just in case things change in the future, but otherwise hide the nodes.  I guess this means returning a 403 or 404 if someone or a search bot requests the page, so that local users will be unable to see them and bots will eventually remove them from their indices.
I've disabled the poll module and disabled all the user permissions having to do with polls, so no new polls will get created.  However, if someone requests the page via its URL, they get a normally-themed page with the poll's title (but no other content).  I tried marking one of the polls as "not published", which comes pretty close to what I want: a normally-themed 403/access denied page.  This would require my hacking the "published" state of all the poll nodes to "false", which I guess is better than nothing, but I was hoping for a hook function that would produce the same result, but without messing around in the database.  Any advice out there?  Thanks!


texts: How do I add taxonomy to my custom entity?

texts:
I am working with a custom entity and I would like to be able to add taxonomy to the entity.  The drupal 8 entity documentation is lacking.

I have tried reading Node.php and term.php entitiy files but I don't understand how any sort of taxonomy is linked to any other entity though this.

Do I need to change something in my entity definition to allow taxonomy to be added? Or is there a way to access the taxonomy entity?

Edit:  I am working on the same pattern to add this to the install file of my module

'category' => array(
                'type' => 'varchar',
                'not null' => TRUE,
                'default' => '',
                'description' => 'The section front  to appear on',
            ),

this is the exception that I get trying to install the module

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error [error]
or access violation: 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 'NOT NULL DEFAULT '' COMMENT 'The section
front  to appear on',


texts:
What is a good way to delete a stuck batch in Drupal 7?

It is on a production server, we are using the Background Batch module so it shows us which one it is at admin/config/system/batch/overview.

I know I can just run a query and delete that row from the DB but wondering about other cleanup I should do too.


texts: How to programatically remove parent form taxonomy term?

texts:
I try to remove programatically all parents form my taxonomy terms. But I can't get it working. I tried this code:

$vid = 18;
$tree = taxonomy_get_tree($vid);
foreach ($tree as $term) {
   $term->parents = null;  # Does not work
   $status = taxonomy_term_save($term);
}

But after saving (although the function returns 2) the parents are still there. What is wrong?


texts: Does CAPTCHA Module still disallow page caching?

texts:
I'm trying to manage spam entries into my websites' contact forms. Currently using the Drupal Captcha module for Drupal 6. http://drupal.org/project/captcha

Based on this report: http://3dg.me/web/drupal-caching-incompatible-with-captcha - I learned that page caching can interfere with the operation of the module. Is this still relevant? Does this apply to allow image captcha based modules?


texts: Proper way to customize Drupal.ajax.prototype.beforeSend and Drupal.ajax.prototype.success functions

texts:
Is there any proper way to customize Drupal.ajax.prototype.beforeSend and Drupal.ajax.prototype.success functions? I just wanted to add additional effect to the inserting and removing of Throbber container, but I couldn't find any way to achieve this. Then I created a new js file and copied the whole functions and modified them. After that I added the file with drupal_add_js() with additional check, like this:

if (!path_is_admin(current_path())) {
    drupal_add_js(drupal_get_path('theme', 'carroza') . '/js/custom.js', array('type' => 'file', 'group' => JS_THEME));
  }

This is working fine, but I think this kind of approach is wrong and is not convenient.


texts: Is it possible to edit Views code instead of the ui?

texts:
I'm aware that I can export and import a Views code. I'm wondering if there is a way to edit and add relationships or contextual filters of a current view within the code instead of the UI.

The reason is sometimes its just easier to add the code rather than drilling down to the relationship within the UI.

If not, I guess the workaround would be to export, then change, then import and overwrite. Not sure how this will effect the site if the views were created from a module installation.


texts: I have a problem configuring search on my site using Custom Search as well as Search Autocomplete. I set the both modules' options to include only 2 types of content. Within those types I have 4 nodes with titles matching the pattern: ABC-.... which are presented as autocomplete item. However when I enter ABC and press enter, only one of those node is found. What could be the cause?


texts:
I'm trying to do something before my invoice saves. In my invoice module I have:

function invoice_node_presave($node) {
  var_dump($node); die;
  if ($node->type == 'invoice') {
    // If true we are creating a new invoice
    if (intval($node->invoice_number) == 0) {
      // Get new invoice number
      if (intval($node->user_defined_invoice_number) > 0) {
        $node->invoice_number = $node->user_defined_invoice_number;
      }
      else {
        $node->invoice_number = _invoice_get_new_invoice_number();
      }
    }
  }
  ......
}

As you see I have a var_dump($node) & a die; . This works perfect. But then when I want to add the following in my template.php :

function xmed_node_presave($node){
  dump($node); die;
  if (($node->type == 'invoice')) { //node has not been saved
      dpr($node); die;
  }

}

He doesn't die. He just runs... Also the rest of functions in my template.php like function xmed_preprocess_page(&$vars) work.


texts: Change crop focus for specific styles on certain existing images

texts:
I just migrated a 15,000 story news website and am doing some quality testing on that migration.

The site uses about 5 image styles for various things, including a REALLY wide one (~960x400px) at the top of every story. This works awesome for images with horizontal/landscape orientation, but causes some weird cropping for images with vertical/portrait orientation.

I don't want to use a solution like imagefield_crop, which will change the cropping on all images (square thumbs are less problematic, for instance). Any idea of modules that allow me to override the default cropping focus from Image Styles for specific styles on specific images?

Thanks!

(Additionally, these images are in Field Collections, so any module suggested should work with that. Currently, it seems that imagecrop does not.)


texts: Added items to registration form and get "Notice: Undefined property: stdClass"

texts:
I added 2 items to the user registration form Phone Number and Carrier. When I register a user or edit one i get the following error.
Notice: Undefined property: stdClass::$phone in user_account_form() (line 1066 of /var/www/capaug/modules/user/user.module).
Notice: Undefined property: stdClass::$carrier in user_account_form() (line 1076 of /var/www/capaug/modules/user/user.module).

Here is the code for the user registration:

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

  $account = $form['#user'];
  $register = ($form['#user']->uid > 0 ? FALSE : TRUE);

  $admin = user_access('administer users');

  $form['#validate'][] = 'user_account_form_validate';

  // Account information.
  $form['account'] = array(
    '#type'   => 'container',
    '#weight' => -10,
  );
  // Only show name field on registration form or user can change own username.
  $form['account']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
    '#required' => TRUE,
    '#attributes' => array('class' => array('username')),
    '#default_value' => (!$register ? $account->name : ''),
    '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
    '#weight' => -10,
  );

  $form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->mail : ''),
  );

  //Phone Number Entry
  $form['account']['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone Number'),
    '#maxlength' => PHONE_MAX_LENGTH,
    '#description' => t('A valid Telephone number. Numbers only, no parentheses or dashes.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->phone : ''),
  );

  //Carrier Selection
  $form['account']['carrier'] = array(
    '#type' => 'select',
    '#title' => t('Carrier'),
    '#options' => array(t('--- NONE ---'), t('AT&T'), t('NTelos'), t('Sprint'), t('Straight-    Talk'), t('T-Mobile'), t('Tracfone'), t('Verizon'), t('Virgin Mobile')),
    '#description' => t('Your phone service provider. Select "None" for home phones.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->carrier : ''),
  );

Where do I have to define those variables to get them to work?

Thank you all!


texts: Feeds: How to import images using CSV Node Import?

texts:
I try to use Node Import clone with an extra image field to import nodes with images attached.

Without success, I try to upload content from a local file (s).

I use CSV parser and Node Processor.
My content type has a image field called Photo I mapped to the csv format using the mapper.

I am using Windows as a local feeds source and Drupal 7 as a server.

How to import images using CSV Node Import ?
What should be exactly the image file path in the csv file ?


texts: Rate module not count until reloading page

texts:
I create a views block for comments.
Everythings is fine until I add: Comment: Nid CONTEXTUAL FILTERS

When click on "vote", it will remain the point result, and saving... until reloading page.


texts: Create referral url for user and add UID to hidden field when url used

texts:
I need to create referral url for authenticated user. This url should be url for webform, and it should include user UID.

When user shares this url and someone uses it to fill webform it should set UID to the hidden field in webform - so admin can see whose referral url was used.

How to create this url?
How to set referred user UID to hidden field?

Can someone point me to the right direction where to start implementing this?


texts: CKEditor not showing after enable clean url in drupal 7

texts:
I am facing some problem with ckeditor. It works perfect when clean url option is disabled, but after enable it only getting textarea. One more thing I have noticed that it is showing again after deleting all the content from textarea and saved it.

I have some other module installed.
WYSIWYG Filter - enabled, IMCE - enabled, CKEditor - enabled, IMCE Wysiwyg API bridge - disabled, jquery update - enabled, Wysiwyg - disabled


texts: Using chinese character in drupal_mail_send() generates unreadable character

texts:
I am using code similar to the following one.

$message = array(
  'id' => 'named_fund',
  'to' => $email,
  'subject' => '恭喜您！',
  'body' => '恭喜！',
  'headers' => array('From' => 'Company Name <example@example.com>', 'Content-Type' => 'text/html; charset="utf-8";'),
);

drupal_mail_send($message);

When I use Chinese characters for the "From" header, I get strange characters. Why?


texts: Need advise to link a cck field with several values to another cck field

texts:
I am going to try to explain what I need to do. I have a content type called Goals. This content type has a cck text field. This field can has several values in order to write a goal in each value of the field.

What I want is when a user write a new goal (each goal is a value in the same cck field), he has a list tex field to point if he completed the goal.

How can i do this? What is the best option I have?

After I would like to create I view to show the goals completed and incompleted, so the goal and completed-incompleted must be linked in certain way.

Thanks a lot!


texts:
I have created a REST export view of contents.

I have all default configuration. I set my path to "/api".

Now when I try to add another rest export view on it, and create a contextual filter and I want to provide the path into "api/%", I am getting "Path is empty" when I click apply.


texts: hook_menu implementation page not found error drupal 7.10

texts:
I am trying to figure out why hook_menu implementation is not working anymore after upgrade from 7.4 to 7.10 for a custom module
Menu links were working properly until update to latest version. after update all custom module links are deleted from table menu_links and menu_router.

ex. of one of the menu link:

$items = array();

$items['a/main'] = array(
'page callback' => 'main',
'description' => 'Main front page',
'access callback' => TRUE,
);

return $items;

This code was working properly in 7.4 but not anymore.
Have tried to do all cache clearing, menu_rebuild()... etc. nothing seems to work.

Even tried to copy sample code from hook_menu API page like
    function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
    }

function mymodule_abc_view($ghi = 0, $jkl = '') {
// ...
}

and does not work as well.

So I am wondering if anything changed after 7.4 version or I am really missing obvious details?

Thank you for comments.