texts: How can I fix this error and upload files?

texts:
I have a simple form with just a field to upload a file on a Drupal 8 site using the Webform module 6.0.1. If I test the form using webforms test tool, the file gets uploaded fine, it displays the loading icon for couple seconds and its ready to upload, but if I try the same in a page with the form embedded as a block, I can not upload the file it will always show me the following message if I try to submit the form, no matter how long I wait.
"File upload in progress. Uploaded file may be lost. Do you want to continue?"

Just for testing, I increased the max upload file to 2GB and the file I'm uploading is just 5kb. All the .js libraries I can think of are on my template.info.yml file. (core/drupal, core/jquery, core/drupal.ajax) The private folder has been set up in my settings.php and has the permissions set correctly the .htaccess file is also set as recommended for Drupal. I have try to upload the files in the public folder just as desperation but I get the same error
Any help will be appreciate.


texts: How to insert content type fields directly into Views

texts:
I am wanting to place a view into my sidebar like yahoo answers Yahoo Answers TOP Right Sidebar. The block would display the actual fields (to be filled out) from the content type, once submitted it would create the content.

Is there a specific module for this or can it be done directly with views somehow?

Thanks!


texts: How to remove Field Group module label length limit?

texts: How to remove Field Group module label length limit (which is 128 characters). Is there any module to change the default length?


texts: Changing filter plugin settings before they are saved

texts:
(This is for D8, although parts of this filter settings API were already in D7.)

As far as I understand, a filter plugin exposes its settings solely with FilterBase::settingsForm() - the central architecture then automatically stores the submitted form values and loads them when creating the plugin instance, so that a filter plugin can find them in $this->settings.

I'd like to reorganize and clean up the submitted form values before they're stored, but I'm not sure where to intercept the form. Should I attach a #validate or a #submit? If the latter, how do I ensure that my #submit runs before FilterFormatInterface::submitForm()?


texts: Unable to use user fields from the global variable $user

texts:
I have created a module where I am declaring $user as global variable in hook_init().  I can access the values of $user->x_field in page.tpl.php. When I try to use $user->x_field in hook_contents($display), it causes the following error:

  Undefined variable:x_field

Can I use the user fields in hook_contents()? Am I doing it the wrong way?


texts: How to set required to TRUE or FALSE based on the GIVEN #states?

texts:
I have problem with the required. It does not return a required validation when I clicked submit button. What is wrong with this code?

$form['fieldset1']['last_name'] = array(
  '#type' => 'textfield',
  '#title' => t('Last Name'),
  '#states' => array(
    'required' => array(
      ':input[name="payment_method"]' =>  array('value' => array('credit', 'debit')),
    ),
  ),
  '#attributes' => array(
    'placeholder' => array('Last Name'),
  ),
);


texts: How can I create a view showing count of users by birth year?

texts:
I want to create a table showing a count of number of users by birth year. Right now I've done the following:

Create a view of profiles rendered as a table (no grouping fields, though I've tried grouping to no avail)
Create two fields:

Birth date, rendered as four digit year, aggregated as "Group results together"
Profile ID, aggregated as COUNT DISTINCT

Sorted these by descending birth date

The problem is that this does not group the dates by year - it still groups the dates by day. Right now, rather than one line in my table for each year, I'm getting something like this:

2017 | 1
2017 | 2
2017 | 1
2017 | 1
2017 | 3
2017 | 1

...the left column being the four digit year and the right column being the number of users born on a particular day in 2017. The above should have rendered as:

2017 | 9

How can I get my table to show a count of users by birth year?


texts: How to update the number of views from the statistics module?

texts:
How do I change the number of reads/views from the statistics module of a node to a new number

what i want to do is match the # of views of a youtube video to a drupal website hosting the same video?


texts: How do I tell Twig not to print any form field?

texts:
I am trying to theme a form in Drupal 8.

This is the template that I am using which is basically from form.html.twig

<form{{ attributes }}>
{{ element.app_theme_settings }}
{{ element.a2 }}
{{ element.a3 }}

 {% print remaining required form fields. %}
 {{ children }}
</form>

My problem is I want to print children variable but without app_theme_settings, a2 and a3 children. In Drupal 7 we could use unset function, but in twig I am not sure what to use. I know I can use without filter, but it does not accept the array argument so I have to write name of each element already printed.

 {{ children|without('app_theme_settings','a2','a3' }}

How can I print children without specifying the name of each field one by one?


texts: Sending email notifications to webform submissions

texts:
I am trying to create a rule that will send an email to a list of webform submissions, notifying them when new content is created. So far, here's what I have:

Event: after saving new content of type [type]

Conditions: content is of type

Actions: Using a Rules view display, I'm grabbing the webform submissions, and then looping through to send mail to the value of the webform submissions.

All works well, until I need to send the mail. Rather than looping through and sending to the email addresses that I'm trying to get from the webform submissions, it appears to be sending to the submission ID instead.

I'm sure there's something I'm missing in either my rules view display, or the rule itself, but I've hit a wall. Anyone know what I might be doing wrong?


texts: Updating a field value in database via submit handler doesn't update the user profile in UI

texts:
I've created the field "Attending" that is attached to the user profile.
I have created a form with one checkbox element; when submitted, I've confirmed that the attending_fielddatabase is being updated with the current value (0 or 1), but when I view the user profile through the UI, the updated value isn't being displayed.

The submit handler I am using is the following:

function rsvp_aform_submit($form, &$form_state) {
  global $user;
  db_query("UPDATE {field_data_field_attending} SET field_attending_value = :val WHERE entity_id = :eid", array(':val' => $form_state['values']['rsvp'], ':eid' => $user->uid));
  drupal_set_message(t('Your form has been saved.'));
}

Do you have any idea?


texts: How can one display the FULL URL of his homepage?

texts:
I have already asked the question and got too much of a short answer, which didn't allow me to actually solve the problem. I'm sure that elaboration is needed, so more users could enjoy an answer. The question:

Is it possible to display the full URL of the home page in Drupal 7, like:

www.example.com/The-best-example-possible

I'd like to display the full URL of the home page as displayed above, and not only the Pure URL which in this case is:

www.example.com

How can that be achieved? what file\s should i go for doing that, where can such file\s be found?, what exactly to change, etc.

Thank you !


texts:
I am using Drupal 8.4.
I am trying to dynamically create/update field data for a content type.

Is there a way to get the type of a field (e.g. text, image, file upload) for a content type?


texts: user login form: name and password default values

texts:
Currently, when the user is loggged out, on user login form, the username field is filled with text, which probably is taken from a cookie (not sure) - it is the name of someone who logged in before. The password is also filled with dots, representing previously logged in password.

How to prevent it, i.e. always display username and password fields empty?

P.S. Why I need this? Because the requirement is that in the user name box there is a placeholder behavior with text "Username". (HTML5 placeholder). I noticed that it works well when the browser has no username remembered and does not work at all when the browser remembers the username and password.


texts:
I have a bunch of nodes that are of the type expert. Expert nodes have a flexible sized list of expertise categories. So an expert would be a person, (Patrick McDougle, Patricia O'Connor …) and a expertise category would be (Autism, Aging, Bulimia …) Using Views 3 and Drupal 7 I would like to end up with something like this:

Aging
Patricia O'Connor

Autism
Patrick McDougle
Patricia O'Connor

Bulimia
Patrick McDougle
...

Is there a way to do this, without having to create my own views template?


texts:
I have been getting this error: Warning: strlen() expects parameter 1 to be string, array given in drupal_validate_utf8().

After troubleshooting I was able to figure out line that cause this error that is on a if stament.

  if (empty ($form_state['num_boxes'])) { // Line with the problem.
    $form_state['num_boxes'] = count($boxes) + 1;
  }

After researching I believe that have to deal something with filter_xss_admin. However, it seem unclear to me of how to implement with my code.

Update 1 - Apparently, the code that I provide did not show the error. I have provide more code.

/**
 * Form builder.
 */
function custom_module_overview_form($form, &$form_state) {

  $form['#tree'] = TRUE;
  $boxes = variable_get('custom_module_package_sizes', '');
  if (empty($form_state['num_boxes'])) {
    $form_state['num_boxes'] = count($boxes) + 1;
  }

  $form['sizes']['#prefix'] = '
';
  $form['sizes']['#suffix'] = '
';

  for ($i = 0; $i < $form_state['num_boxes']; $i++) {
    $form['sizes'][$i] = array(
      '#type' => 'fieldset',
      '#title' => t('Package'),
      '#description' => t('Enter the dimensions of the packing box.'),
      '#attributes' => array('class' => array('physical-dimensions-textfields')),
      '#attached' => array('css' => array(drupal_get_path('module', 'physical') . '/theme/physical.css')),
    );

    foreach (physical_dimensions() as $key => $dimension) {
      $form['sizes'][$i][$key] = array(
        '#type' => 'textfield',
        '#title' => filter_xss($dimension)['name'],
        '#size' => 15,
        '#maxlength' => 16,
        '#field_suffix' => '&times;',
        '#prefix' => '
',
        '#suffix' => '
',
      );

      if (isset($boxes[$i][$key])) {
        $form['sizes'][$i][$key]['#default_value'] = $boxes[$i][$key];
      }
    }
    unset($form['sizes'][$i][$key]['#field_suffix']);

    $form['sizes'][$i]['unit'] = array(
      '#type' => 'select',
      '#options' => physical_dimension_unit_options(FALSE),
      '#prefix' => '
',
      '#suffix' => '
',
    );

    if (isset($boxes[$i]['unit'])) {
      $form['sizes'][$i]['unit']['#default_value'] = $boxes[$i]['unit'];
    }
  }

  $form['packing_add_more'] = array(
    '#type' => 'submit',
    '#value' => t('Add More'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#submit' => array('custom_module_admin_add_more_submit'),
    '#ajax' => array(
      'callback' => 'custom_module_admin_add_more',
      'wrapper' => 'boxes-fieldset-wrapper',
    ),
  );

  $form['packing_submit'] = array(
    '#type' => 'submit',
    '#prefix' => '
',
    '#suffix' => '
',
    '#value' => t('Save'),
  );

  drupal_add_library('system', 'drupal.ajax');

  return $form;
}

Update 2 - I believe that the issue is in this block

foreach (physical_dimensions() as $key => $dimension) {
          $form['sizes'][$i][$key] = array(
            '#type' => 'textfield',
            '#title' => filter_xss($dimension)['name'], // Removing this line would make the page disappears.
            '#size' => 15,
            '#maxlength' => 16,
            '#field_suffix' => '&times;',
            '#prefix' => '
',
            '#suffix' => '
',
          );

On the line '#title' => filter_xss($dimension)['name'],

How can I fix this issue ?


texts: Conditional patterns with automatic nodetitles

texts:
I`m using automatic nodetitles module to hide and autogenerate the title of one of my content types. My question is:

Is it possible to use conditional rules to define which pattern to be used when certain conditions is met? I need the pattern to be X if a certain field in the node is present, another if not.

Thanks,


texts: Patch Status for 'cweagans/composer-patches'?

texts:
It seems that 'Drush Patch File' (https://bitbucket.org/davereid/drush-patchfile/src/master/) isn't compatible with Drush 9. It, however, has one important function - Patch Status - which enables developers to check that all the required patches were successfully applied.

I was unable to find any way how to do this via the actually recommended Composer patch management (cweagans/composer-patches)... Is there any way how to (via Composer or Drush command) check the status of the patches? Or is there a clone of 'Drush Patch File' working with Drush 9?

Any help highly appreciated!


texts: How to sql-sync database between two remotes which share the same host?

texts:
I've two remotes: @source and @destination.
I'm trying to transfer the database from dev to test environment by using sql-sync:
$ drush -vy sql-sync @source @destination

But at the end drush complains that:

The source and destination cannot both be remote.
rsync error: syntax or usage error (code 1) at main.c(1166) [Receiver=3.0.9]

Both remotes are on the same machine, but they're using different path.
I'm using latest drush 7.0-dev.
Is there any workaround?


texts:
I am newbie to drupal i have integrated the Apache solr search module and its working fine. I have disabled the drupal's core search.

Now I am creating my own custom module. How can I make the Apache Solr module search functionality work with my custom module? I need sorting and pagination along with search.


texts: How can I create a description label in the CCK  form?

texts:
I have a form with CCK.  I have the fields into fieldsets.  I need to add a text.

Fieldset a
   field1
   field2
fieldset b
   field3
   field4
   field5
   Here is the text (is not field)

How can I add a text in the "fieldset b", below the "field 5" and before the save button?

Thanks.


texts: Using Fields as Attributes in Node Templates

texts:
What is the best practice for using a field as an "attribute" in a node template with Drupal 7?  I am using the term "attribute" loosely here to mean something that can't be concretely rendered as an HTML fragment; rather, it gets rendered inside an HTML fragment somewhere in a template.

The field API makes it very easy to wrap a "content" field with HTML so it can be rendered in a template, many times with out needing to edit the node template at all, due to the way render trees work.

Consider a content type such as

Title (title)
Body (body)
Extra (field_extra)

Where field_extra is just something that I want to tack onto the node title, eg

<?php if (!$page && $title): ?>

<?php print $title ?> &mdash; <?php print $extra; ?>

<?php endif; ?>
print render($content);

This is a very, very simplified example to illustrate what I am talking about.

I could just access

$extra = trim($field_extra[0]["safe_value"]);

but I would have to go through some show()/hide() logic depending on how things where configured, and directly accessing fields is discouraged.

I could make a theme_field(), such as

function mytheme_field__field_extra ($variables)
{
  $items = $variables["items"];
  return count($items) == 0 ? "" : trim(drupal_render($items[0]));
}

and then use render(), but I would still have to go through the show()/hide() shenanigans and I am not really rendering the field, just trying to get a plain version of it to use somewhere.

Or, should this really be handled by a template_preprocess_node(), eg

function mytheme_preprocess_node (&$variables)
{
  $node = $variables["node"];
  $language = $node->language;

  if (isset($variables["field_extra"])
      && isset($variables["field_extra"][$language])
      && isset($variables["field_extra"][$language][0])) {
        $variables["extra"] = trim($variables["field_extra"][$language][0]["safe_value"]);
  }
}

I know all of these will work.  I am really interested in what is the best practice here.  I suspect that the template_preprocess_node() is the best way to handle this, but I have not seen anything definitive about this case.

Thanks.


texts: admin/commerce/products/add page says "You have not created any product types yet" when I have

texts:
Somehow, the Drupal Commerce page at admin/commerce/products/add is failing to recognise that I have product types and is giving this misleading error:

  You have not created any product types yet. Go to the product type creation page to add a new product type.

From reading this discussion and a look at the code here it looks like the Commerce module on this page bizarrely gets the list of product types from looking at the menus. There's a heap of "what worked for me was moving X to Y in the menus" but they all seem to be slightly different and match older menu naming conventions. This issue appears related but isn't. I have editted the Commerce menu and would like to keep my editted menu how it is.

How can I make sure that Commerce recognised my product types on this page? What has to be where for this page to recognise product types (or even better, is there a way to make it happen the normal way via entities instead of via menus?)

I've also tried bypassing my broken admin/commerce/products/add page completely with a redirect, but the redirect is ignored.

I've also tried moving my Products > Create Item auto-generated menu links back under Store in the Management menu, and creating new menu links to those pages under Store in the Management menu, but neither works.


texts: creating and theming register form in drupal 7

texts:
There are many links in websites that talk about this question, but I'm really bewildered how to do it, I've tested many solutions but I failed.

this is my code to add register form into a page

<?php
    if(user_is_anonymous()) {
    $form = drupal_get_form('user_register_form');
    print drupal_render($form);
    }
?>

it is all I know of register form !
it prints all the fields of registered users. I also added other fields like mobile, phone and ... from admin/config/people/accounts/fields.

what is the most straightforward solution to theme the form? text fields and ... ?


texts: Check to see if content exists; if not, create it

texts:
I have two node types that are related by a node reference. Essentially, content type A is a container, and content type B is an item. For illustration sake, I'll call content A Box and content B Item. the Item has a number of taxonomy terms that are shared with Box. Again for illustration sake lets call them color and size. What I'm trying to do is set up a rule that does the following:

On Creation of an Item ( actually before the content is save) check to see if there is a Box that shares both the color and the size of the item.
If one exists, assign the new item to that box (via node reference).
If one does not exist create the box, then assign the new item to that box.

I'm new to the Rules module, and although it seems really powerful, I'm just not sure that this particular use case is possible. The part that I'm most unsure about is how to check if the box with certain terms exists.


texts: Text does not get highlighted in views using search api solr

texts:
I'm trying to highlight my search key in the result of a view using apache solr + search api solr module.

I've created a server + index using the search api solr module.

I've enabled highlighting option on both of them (In advanced setting on the server and within the filters in the index part)

I've created a view and exposed  Search: Fulltext search (exposed)

But the search word does not get highlighted.

When i'm using the "search api pages" module, i do get the search key highlighted.

Any ideas?


texts: views exposed filters programmaticaly adding content titles as select list with content types

texts:
I have created a view which displays content types as select list with exposed filters as my requirements, I want to add a select list of content titles.
Example I have an content type article which consist article-1,article-2,...article-8 content titles.I want two select list boxes ,If I select articles in content type select list box .I should get content titles of articles as articl-1,article-2...article-8 in other .how can i get content title from exposed filters and display it programmaticaly.


texts: how to protect my form by checking that 2 values are not the same?

texts:
I have a contact form created with webform module.
I have already add recaptcha on my form, but I received regularly some bad contacts.
To protect my form I want to check that field lastname and firstname have not the same value before the user click on submit button.
how can I do that.
thanks.


texts: How to increase the width to the Omega sub-theme more than 950 usable pixels

texts:
I have created a new sub-theme of the Omega theme (version 7.x-2.1) in Drupal 7.

But I want to use 970 usable pixels instead of 950 pixels as the sub-theme offers in "Default container width".

How can I do this? Shall I change the 960.css file from themes/omega/omega/css/960.css or shall I overwrite the 960.css file form my sub-theme? What you suggest?


texts: Number items in a grouped view, resetting counter with each group

texts:
I've got a view (D7, Views3) that is grouped by a relationship-based title field (set in Format: settings), and I'm using a Global: View result counter to give each item a number. This is how output currently looks:

Some group

1...An item

2...Another item

Another group

3...More items

4...Still more items

5...Even more items

It's counting rows regardless of position in groups. I want it to reset the counter with each group, to look like this:

Some group

1...An item

2...Another item

Another group

1...More items

2...Still more items

3...Even more items

Seems like a simple enough task - but I can't find any options relevant to this. I don't mind writing some code to achieve this, but Views is so dense I have no idea where to start.

Can this be done without coding up some hooks? If so how?

If not, where and how in the thicket of data that is a views object could I identify where within a grouping each Global: View result counter field row is?

EDIT: looking at the very simplistic code in views/handlers/views_handler_field_counter.inc, it looks like a custom module based on this code would be the best option, creating a new global field that uses groups instead of the pager. This would need to find data about each group (probably in $this->view somewhere?), and would identify its own row's position in the appropriate group. Is this possible? Again, not really sure where to start.

EDIT 2: No sign of useful grouping data in the view object that I can see, but this thread suggests that maybe it's sorting data that should be used for this?


texts: Error displaying block created progamatically

texts:
I am trying to create a block with a form to display inside the block.
Here is my block
<?php
namespace Drupal\fixx_helper\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a block with a simple text.
 *
 * @Block(
 *   id = "ticket_test_block",
 *   admin_label = @Translation("Ticket Admin and Dept Block - Custom"),
 * )
 */

class ticketBlock extends BlockBase
{

public function build()
{

    $form = \Drupal::formBuilder()->getForm('Drupal\fixx_helperAdmin\Form\ticketAdmin');

    return $form;
}

}
?>

This is the form that I created:
<?php
namespace Drupal\fixx_helper\Form;

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

class ticketAdmin extends FormBase
{
  /**
   * {@inheritdoc}
   */
  public function getFormId()
  {
    return 'ticket_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state)
  {

    $form['assign_ticket_admin'] = array(
      '#type' => 'textfield',
      '#title' => t('Employee Name:'),
      '#required' => TRUE,
    );

    $form['department'] = array(
      '#type' => 'email',
      '#title' => t('Email ID:'),
      '#required' => TRUE,
    );
    return $form;
  }

}

This is the plugin error that is showing up when I try to click "place block":


texts: How NOT to redirect using the Rules module?

texts:
I have a comment form in a panel. The path to the panel is user/[uid].

When I post a comment I am taken to another page where all the comments are shown (user/[uid]/comments.) I do not want this, I want to stay on the same user/[uid] page.

Does anyone know how to do this using the Rules module?


texts: I am not able to override the form #access setting

texts:
I cerated a form alter with the file entity media upload browser. I studied this answer of how to alter this form. I then debugged and found that for what I wanted to do, I am in step 4 of the file upload browser as evidenced by the var: $var['#step'] (Integer) 4.

Thus my code so far is:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Form ID = file_entity_add_upload.
 */
function MYMODULE_form_file_entity_add_upload_alter(&$form, &$form_state, $form_id) {
  // Check that this is the fields step.
  if ($form['#step'] == 4) {
  echo 'This is step 4';
  // yep the above prints out.

  // Set access false for the specified field.
  $form['field_usage_restricted']['#access '] = FALSE;

  // Add a dsm after to see what's going on
  dsm($form);
  }
}

You'd think this would get rid of the form field, yet, it's still present. See the dsm below:

I would think that my custom alter FALSE setting would override the TRUE setting but no such luck, the field is still there.

I can use an unset($form['field_usage_restricted']); and that works fine to get rid of the field, but I've learned that ['#access '] = FALSE; is a better way to go, especially when there's ajax in use such as the case here. I do see in the debug that there's a form after build so I wonder if I need to do that?

I tried this on the off chance it would work but still no joy:

if ($form['field_usage_restricted'][LANGUAGE_NONE]['#after_build'][0]) {
  // Set access false for the specified field.
  $form['field_usage_restricted']['#access '] = FALSE;
}

(Note, my field, field_usage_restricted is not a required field.)


texts: How can I show only 3 countries in country list (select box)?

texts:
I'm using SMS User module which validates users' mobile numbers. There's a select box and all countries in it. Users select country and write their mobile numbers.

I want to show only 3 countries in it, but there's no option in admin panel. I looked up the sms_user table. There is a gateway column and country codes writing. That's all.

How can I modify the country list? When I looked into the module code, I found nothing about countries.


texts: Adding like condition to db_select for section of string

texts:
What I am trying to do is find all of the basic pages where their titles contain 'Meetings' for example January Meetings

Here is what I have tried so far

$string = 'Meetings';
    $query = db_select('node', 'n');
    $query->fields('n');
    $query->condition('n.type', 'page', '=');
    $query->condition('n.changed', $time, '<=');
    $query->condition('n.status', 1, '=');
    $query->condition('n.title', '%'.db_like($string), 'LIKE');
    $result = $query->execute();

Which hasnt worked as it is trying to find pages that only contain 'Meetings' in their title.


texts: drupal store and retrieve variable from $_POST array

texts:
This is really simple question for the user who are using DRUPAL for many years.But for me it is creating a big issue.

I already made a form using the drupal form api.But after submit the form I want to store form data in the "$_POST" and print the data to another module's page.I get the data on the 2nd page(module's page where I want to show the form data)when I store the data in $_SESSION or in $_GET array but not get result when I store data in $_POST.What is the proper way to store data in $_POST array and fetch the data in another page?

my submit code is as follows:

function create_kavings_create_form_submit($form, &$form_state) {
    //print_r($_POST);die();
    //$_POST['first_name'] = $form_state['values']['first'];
    //$_POST['last_name'] = $form_state['values']['last'];
    //$arr[]=$_POST;
      $options = array(
      'query' => array(
         'first' => $_POST['first'],
         'last' => $_POST['last'],
        )
      );
      $form_state['redirect'] = array('coupon_preview',$options);
}

On 2nd page I simplly write the following to print the post array:
print_r($_POST);
But is showing blank.


texts:
I need to translate the names of countries in drupal. I am using countries_get_list, looping through the array and saving it in another array but wrapping the country names in t(). I'm not so so sure but it seems this isn't working.
I was doing something like

$new_array = array();
foreach(countries_get_list() as $key => name) {
    $new_array[$key] = t($name);
}
return $new_array;


texts: Can you make a field unique in a content type?

texts:
I have an Employee content type with an ID field.

Can I make the field unique, so that Drupal would prevent me from entering the same ID more than once by mistake?


texts:
Is it possible to add the field field_tags in mymodule_install() like the body field?
I added a body field with node_add_body_field. I can see the field in field_config_instance table. Is there a posibility to add field_tags in hook_install() without doing it in the GUI?

Is it done by field_create_field?

if (!field_info_field('my_field')) {
  field_info_cache_clear();

  $field = array(
    'field_name' => 'my_field',
    'type' => 'custom_field_type',
    'cardinality' => 1
  );
  field_create_field($field);
}

But how to set the values for a default article or gui custom like tags field?


texts: How to add / remove tabs from user profile?

texts:
By clicking on the "My account" link that on the secondary menu on the site, the user is redirecting to the user's profile page.

In this page there are many tabs. Some tabs are there originally, and some tabs created by some modules. I understood how to add tabs to this menu (by simply create view and give it path of /user/%user/XXX).

Is there another way?
How can I remove tabs from the user's profile menu?

Why this user profile menu is not under the menus section of Drupal?

My goal is to remove the following tabs (see screenshot below): "HybridAuth", "Your Questions" and the "Points" tab.


texts: What steps do I need to take to use Drush Make on a Windows machine?

texts: I have the Drush Windows installer. I download the Drush Make module and put it in the drush\commands folder. Still I don't have any luck with Drush Make on Windows.


texts: How can I use full URLs for aggregated assets on a specific route?

texts:
My organization is using an external search application. The results are intended to be wrapped in a header and footer to mimic the appearance of the main website.

I've created a couple of custom routes, /wrapper/header and /wrapper/footer, that simply return a (practically) empty page with a partial template. As far as the markup goes, that's working fine; the search app can pull both and wrap them around the results as intended.

However, on the header, we need to use full URL for the aggregated CSS and JS files. I've taken a look at hook_page_attachments_alter(), but that appears to deal with assets attached pre-aggregation. Is there a way for me to override the URLs inserted to replace the placeholders? The CDN module looked promising, but can't be restricted to work on specific routes.


texts: Why doesn't print module_invoke('user', 'block', 'view', 0); use template files?

texts:
If I invoke the user login block using module_invoke it doesn't use block-user-0.tpl.php. If I drop the block in the right sidebar and print $right it does use block-user-0.tpl.php.

Also, why will it only print the block once so that printing $right and module_invoke only results in one login form?


texts: How does entity_metadata_wrapper work with array?

texts:
This is my code to return value of fields in a content type called library

$wrapper = entity_metadata_wrapper('node',$variables['node']);
$variables['name']= $wrapper->field_library_book_name->value();
$variables['writer']= $wrapper->field_library_book_writer->value();
$variables['detail']= $wrapper->field_library_book_detail->value();
$variables['photo']= $wrapper->field_library_photo->value();

it works right for name, writer and detail but for image it only prints Array(). this is the var_dump() output of this array:

array(13) {
  ["fid"] => string(3) "382"
  ["alt"]=> string(0) ""
  ["title"]=> string(0) ""
  ["width"]=> string(3) "145"
  ["height"]=> string(3) "194"
  ["uid"]=> string(2) "23"
  ["filename"]=> string(15) "n_471_1_img.png"
  ["uri"]=> string(43) "public://library_book_photo/n_471_1_img.png"
  ["filemime"]=> string(9) "image/png"
  ["filesize"]=> string(5) "40854"
  ["status"]=> string(1) "1"
  ["timestamp"]=> string(10) "1389166558"
  ["rdf_mapping"]=> array(0) { }
}

this is my question: how to output the image itself ?


texts: Why do I get the "Class 'Drupal\Core\Database' not found" error?

texts:
I am using the following code.

$conn = Database::getConnection();
$conn->insert('testimonial')->fields(array('name' => $form_state->getValue('name')))->execute();

I get the following error:

  Class 'Drupal\Core\Database' not found

I am using use Drupal\Core\Database;. What is wrong in my code?

Update: i find using namespaces a problem, like now i want to get row count, if insert was successfull or not. i tried with

$result->allowRowCount = TRUE;
if ($result->rowCount() == 0) { }

and for rowcount i added the name space use Drupal\Core\Database;
i get

  Cannot use Drupal\Core\Database as Database because the name is already in use in

and if i remove this . i get

  Call to undefined method Drupal\Core\Database\Driver\mysql\Connection::rowCount()

How to use namespaces exactly. like i am assuming if i do

  use Drupal\Core\Database

then all the classes in that namespace and all the children namespace should get inehrited. Is this right ?


texts: field_view_value() returns no items in Computed Field

texts:
I am trying to compute the value of a field using the Computed Field module.
I need to get the formatted value of a field field_get_items() and field_view_value().

I think there should be no problems with this procedure as this method seems to be common practice to retreive the field value.
However, I am able to obtain the individual items itself, but the render array is not being generated.

$fields = field_get_items($entity_type, $entity, $fn_it) returns an array containing the individual items.
field_view_value($entity_type, $entity, $fn_it, $v) returns an array with 0 elements.

$fn_it = 'field_autors_it';
$fn_ext = 'field_authors';

$fields_it = field_get_items($entity_type, $entity, $fn_znes);
$fields_ext = field_get_items($entity_type, $entity, $fn_ext);

// Render authors if they exist
dpm($fields_it); // < Containing instances' data
if($fields_it && count($fields_it) > 0) {
  foreach($fields_it as $key=>$v) {
      dpm("Item: "); dpm($v); // < Valid item

      $render_array= field_view_value($entity_type, $entity, $fn_it, $v);
      dpm($render_array); // < This results in (Array, 0 elements)
      $fv = render($render_array);
  }
}

Computed Field provides several of the variables used above:

The variables available to your code include: &$entity_field, $entity_type, $entity, $field, $instance, $langcode, and $items.

And the module's example of getting rough field data is even like that:

Here's a simple example which sets the computed field's value to the value of the sum of the number fields (field_a and field_b) in a node entity:

$field_a = field_get_items($entity_type, $entity, "field_a");
$field_b = field_get_items($entity_type, $entity, "field_b");

I also tried getting the rough data by field_view_field() - no results either.

I have no clue what I'm doing wrong. Any idea what I'm missing?

Best, e.


texts: How can I access this site as the administrator?

texts:
I have a dev site that I cannot access that contains content ad structure I want to extract. To gain access I created a new dev website and copied over the contributed modules and theme I am using. I then imported the database containing the data.  When I go to the custom home page there is no login (I had not yet added it to the panel containing the home page display).  To access the site, I must do one of two things:

Access the site using Drush.  I tried using Drush user-login which returns a link "http://default/user/reset/1/..." It is not clear how to use the link.  Using it directly as-is leads to an unknown website search.  Using it as example.com/default/user/reset/1/...  leads to a page not found error.  Having never done this before, I am not sure what to expect.
If I could change the theme to a standard one such as Bartik through the database or other means I would then have access to a login block.  Where is the current theme stored?

Any other suggestions gratefully accepted:)


texts:
In the project I am working on I have created a theme hook that renders a .tpl.php file:

/**
 * Implements hook_theme().
 */
function my_module_theme() {

  $theme['my_module_list'] = array(
    'variables' => array(
      '#markup' => array(),
    ),
    'path' => drupal_get_path('module', 'my_module'),
    'template' => 'templates/my_module_list',
  );

  return $theme;
}

Then I want some JS and CSS to be added only when this theme hook is used in the current page. Thus I implemented of theme_preprocess_hook() as such:

/**
 * Implements template_preprocess().
 */
function my_theme_preprocess_my_module_list(&$vars) {
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module.js');
  drupal_add_css(drupal_get_path('module', 'my_module') . '/css/my_module.css');
}

However it appears that the preprocess function is not called every time the hook is used resulting in CSS and JS not being added. What am I missing? Is it bad practice to add it there? And if yes where should I add it in order for it to be loaded only when necessary? I couldn't find any documentation that clarifies it and I've also seen it done other places.

Thanks a lot in advance :-)


texts: Redisplay Captcha on form error in Ajax form submit

texts:
I have a Fancybox form and the form is sent via Ajax. I know that there is the error about "reuse attack" for Captcha, but this is not my case.

When I wrong the form (some required fields missing) I see the fieldset of Captcha, but no Captcha inside. It's empty.

How can I fix this ?


texts: Ajax User login failing with "Username field is required", "Password field is required"

texts:
I am trying to set up an AJAX login box for a site, using the following code:

function THEME_form_user_login_alter (&$form, &$form_state) {
   $form['actions']['submit']['#ajax'] = array(

        'callback' => 'user_login_submit',
        'wrapper' => 'user-login',
        'effect' => 'fade',
        'speed' => 'fast',
        'method' => 'replace',
    );
}

I get an Ajax error on form validation, I am thinking I am using the wrong callback but I can't figure out which one would work, and I couldn't find any example out there.. Any suggestion?

This is the error message:

  An AJAX HTTP error occurred. HTTP Result Code: 200
  Debugging information follows.
  Path: /parce/system/ajax
  StatusText: OK
  ResponseText: [{"command":"settings","settings":{"basePath":"/parce/","pathPrefix":"","ajaxPageState":{"theme":"parce","theme_token":"PFPo8K2w-7tUSndM3muIGW4Gpq-X8TT4-fR4ZmVcxD0","css":[]}},"merge":true}]
  Uncaught exception thrown in session handler.
  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
  Column "uid" cannot be null:
  INSERT INTO {sessions} (sid, ssid, uid, cache, hostname, session, timestamp) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6);
  Array(
   [:db_insert_placeholder_0] => -nLyLCVNED-8LSAd6NoZ8znhzZAoUVMNutGmi7ObAQ8
   [:db_insert_placeholder_1] =>
   [:db_insert_placeholder_2] =>
   [:db_insert_placeholder_3] => 0
   [:db_insert_placeholder_4] => 183.16.201.97
   [:db_insert_placeholder_5] => messages|a:1:{s:5:"error";a:2:{i:0;s:27:"Username field is required.";i:1;s:27:"Password field is required.";}}
   [:db_insert_placeholder_6] => 1308899744
  ) in
   _drupal_session_write() (line 203 of /home/sites/parce/includes/session.inc).


texts: Clear data stored with drupal_static() and cache_set()

texts:
I have a custom module in Drupal 7 where I am caching data from REST calls using drupal_static() and cache_set().

function _mymodule_call() {
  $data = &drupal_static(__FUNCTION__);
  if ( ! isset($data) ) {
    if ($cache = cache_get(__FUNCTION__)) {
      $data = $cache->data;
    }
    else {
      $data = my_api_call();

      if ( is_object($lists) ) {
        // cache for one hour
        cache_set(__FUNCTION__, $data, 'cache', time() + 3600);
      }
    }
  }
  return $data;
}

I want to make an admin feature where we can specifically clear these cached values. I suppose the cache key would be _mymodule_call. How do I clear them from the cache?


texts:
I've built all my site apart from the frontpage which right now shows:

No front page content has been created yet.

The frontpage will be the most complex page of all, containing a lot of boxes (blocks) which will be presenting lists of items.

I've got 2 solutions for this problem and I'd like to know which one is best.

solution 1 - blocks

create the ~10 blocks that the frontpage needs
make them translatable
use description prefix "front -" for easier identification in admin/structure/block
configure "Only the listed pages": <front>
somehow remove the "No front page content has been created yet" message

This solution seems very tunable. The CM will be able to do whatever he wants with the individual view blocks of the frontpage.
On the other hand there will be too many blocks in the administration page (but only 1 for all languages).

solution 2 - node

create a node
the node should be of a type which has fields for configuring the fetching and displaying of items. e.g fields:

int: number of news to fetch
int: number of events to fetch
bool: should display teaser
html: teaser content
etc

in admin/config/system/site-information set that node as Default frontpage

The drawback of this is that I should implement the fetching and display, and if the CM wants to change something that the content type does not support I'll need to implement it.
On the other hand I'll have full flexibility in HTML if I provide a separate template just for this content type.

So, is there a definite winner between those 2? Also note that, for various reasons, I don't want to use panels.


texts: How to avoid writing to database in form submit?

texts:
I have a webform and I need to validate a condition before you type in the database.

Use the hook_form_alter, this is my code:

function validate_entry_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'webform_client_form_1'){
    $form['#submit'][] = "_validate_entry_webform_client_form_submit_handler";
  }
}

/* function HOOK_FORM_SUBMIT */

function _validate_entry_webform_client_form_submit_handler($form, &$form_state){
  $option = $form['submitted']['eventos']['#value'];
  $data_total = db_query("SELECT count(data) FROM webform_submitted_data WHERE data = $option")->fetchField();

  print_r('<pre>');
  print_r($data_total);
  print_r('</pre>');
  exit();
}

I've noticed that my function to handle the submit is handled when it wrote in database.

I need a "hook" where you can get all the results before they are written to database. Validate the data and if everything is correct, follow the workflow in database insert.


texts: Advanced search: USASearch compared to Apache Solr Search implemented by Acquia

texts:
I have been asked by a US government agency to compare 2 different methods for
advanced search:

USASearch
Apache Solr Search implemented by Acquia

This agency already has a contract with Acquia to host their Drupal site and this subscription includes (for free) Apache Solr Search which is implemented by Acquia so cost is not an issue when comparing the 2 options since USASearch is free to any government agency.
What are the advantages and disadvantages of these 2 search methods, and which one would you recommend?


texts:
When you set the 404/403 error pages to nodes with a path, how then can you have Drupal go to the 404 path or 403 path instead of outputting the message on the page?

For example, if I type in www.mydomain.com/skdjhfjsdhfjsh, it shows the custom 404 text from my node. But, is there a way to make Drupal send the user to www.mydomain.com/404, so I can use Contexts/Blocks with in the content area of this specific page?


texts: Is there a way to change how Date works when saving dates with the time in 00:00:00? I have a calendar view, and I would like to avoid having events showing as all-day when the are saved with a time of 00:00. Is this possible? I have a content type that cousd either start at 00:00 or end at 00:00, but those are not all day events.


texts: How do I show user custom fields in the comments section?

texts:
I have three custom fields from the user accounts that I would like to display in the comments user posts:

field_agencyname
field_address
field_phone

How/Where would I be able to display this information?


texts: How can I programmatically add data to an address field?

texts:
I'm trying to import user data from a json file. So far I managed to import most of the information, but now I'm stuck on the address field (created with Address module for Drupal 8).
In the json file (exported from a Drupal 7 website), there is city, country code and country name.
How can I import this data into the new field (the machine name is field_address)?
So far I tried using Drupal::entityTypeManager.
$values = array(
            'name' => $user["name"],
            'pass' => '',
            'status' => $user["status"],
            'mail' => $user["e_mail"],
            'field_first_name' => $user["first_name"],
            'field_last_name' => $user["last_name"],
            'field_address' => $city,
        );

        $userStorage = \Drupal::entityTypeManager()->getStorage('user');
        $userEntity = $userStorage->create($values);

It doesn't work: The address field stays empty.
Should I use the sub fields?


texts: Custom links to switch language in Drupal 6

texts:
In my case, I wanted to print the language switch links directly in page.tpl.php, for example with:

English
Deutsch

How can I accomplish this without using the "Language switcher" block? I checked all the modules that comes with the Internationalization project, but I didn't see any hook_block() implementation that outputs the language switcher block.

UPDATED:
I wanted something like: This site is on russian, english and kazakh languages.
This cannot be done with language switcher block.

i've tried this way in page.tpl.php:

<?php
$way = drupal_is_front_page() ? '<front>' : $_GET['q'];
print ''. 'на ' . l('русском', $way). ', ' . l('казахском', 'kk/'.$way). ' и ' . l('английском', 'en/'.$way) .'';
?>

Default language is russian - mysite.com, when i switch to an english - mysite.com/en, as you see it adds prefix 'en'. But now if i want to switch on kazakh language - mysite.com/kk from english the link looks mysite.com/en/kk == it adds en to my URL. How to make this correctly?


texts: How can I correctly attach a file to a mail?

texts:
I am very new to drupal and need to upload a file and sent it as attachment in Drupal 8.
I have created the form element like
$form['candidate_attachment'] = [
  '#type' => 'managed_file',
  '#title' => t('Attachments'),
];

When I submit the form with a PDF file and in the submitform() the data displays for the $form_state->getValue('candidate_attachment');

is Array ( [0] => 1358 )

Code to send email is
// ...
$validators = ['file_validate_extensions' => ['pdf']];
if ($file = file_save_upload('candidate_attachment', $validators, FALSE, 0)) {
  $filepath = file_get_contents($file->getFileUri());
}

// ...
$params['context']['message'] = $test;
$params['context']['attachments'][] = $filepath;
$to = $em["mail"];

$result = $mailManager->mail('system', 'mail', $to, $langcode, $params);

But the email is sending without an attachment. What am I doing wrong? How can I correctly attach the file to the mail?


texts: Content type adding page is not displaying properly

texts: I have a content type and added fields to that . But when try to add a content (the page url is base_url/node/add/content_type) it appear as an administral adding option (Means its not showing the main navigation and side navigation and header images) . Why is it like that ? One thing i noticed that its breadcrumb appear as Home >> Add content, but in real it should be ( that appear in my staging server as Home >> Node >> Add content and appearing the side navigation and main navigation menus )  . I installed node module too .  How could achieve that ?


texts: How can I keep paragraphs of text in one cell when i import data from a CSV file without it making it all one big paragraph?

texts:
I'm using Migrate, Migrate Tools, Migrate CSV to import data from a csv file into my website.
One field I have is Text (Formatted, Long), and this is where I import a bunch of information about my specific item.
If in my csv file I write out something like this in a cell (Using Alt+Enter to create a line break in the cell):
This is paragraph 1 of a block of text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut optime, secundum naturam affectum esse possit. Tu autem, si tibi illa probabantur, cur non propriis verbis ea tenebas? Sine ea igitur iucunde negat posse se vivere? Quod autem satis est, eo quicquid accessit, nimium est;
This is paragraph 2 of a block of text. Duo Reges: constructio interrete. Non enim quaero quid verum, sed quid cuique dicendum sit. Quod quidem iam fit etiam in Academia. Cum ageremus, inquit, vitae beatum et eundem supremum diem, scribebamus haec.
It ends up importing like this into Drupal:
This is paragraph 1 of a block of text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut optime, secundum naturam affectum esse possit. Tu autem, si tibi illa probabantur, cur non propriis verbis ea tenebas? Sine ea igitur iucunde negat posse se vivere? Quod autem satis est, eo quicquid accessit, nimium est; This is paragraph 2 of a block of text. Duo Reges: constructio interrete. Non enim quaero quid verum, sed quid cuique dicendum sit. Quod quidem iam fit etiam in Academia. Cum ageremus, inquit, vitae beatum et eundem supremum diem, scribebamus haec.
Just one big block of text.
Does anyone know of anything special that I need to put into my Excel cell after each paragraph so that Drupal knows to break up each paragraph into its own <p> paragraph tag once imported from the saved .csv file?
I've gone through numerous sites/threads trying to find an answer but I can't quite seem to find anything explaining what I need to do in Excel prior to exporting as CSV to maintain the paragraph breaks.
Note, after I export from excel to csv, i open the file in Notepad and resave as UTF-8 in order to import the content properly in Drupal.
Is this something that is even possible at all?


texts: How to get view name and display ID in template_preprocess_node function

texts:
I'm having some trouble in order to get a view's name and the display ID in a template_preprocess_node function.
I have a custom content type and a view with two different displays.
My idea is to define a variable in the preprocess function related to the content type (using theme_preprocess__content_type_name function), in order to use this variable in the Twig template to switch between the displays, according to the number of results.

I understand that in order to use a variable in the preprocess function, it has to be defined somehow in the template (correct me if I got this wrong).
So my question is: how can I call the view and the display in the node preprocess function?

EDIT 1:
Using Hudri suggestion:

function theme_name_preprocess_node__content_type(&$variables) {

    $route = \Drupal::routeMatch()->getRouteObject();
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    if($view_id == 'view_name' && $display_id == 'display_name'){
        $counter = count($view_id->result);
        $variables['count'] = $counter;
    }
}

Can the variable count be used in the Twig template in an if clause?


texts: Fatal error: Call to a member function difference() on string in error on tpl file

texts:
I'm trying to calculate the value between two fields in my custom node.tpl file. I am trying to convert the code show on http://drupal.org/node/1364744, and I wrote the following one.

$birthday = format_date(strtotime($content['field_date_de_naissance']['#items'][0]['value']), 'custom', 'd/m/Y');
$today = date('m/d/Y');
$age = $birthday->difference($today,'years');
print $age;

I get this error.

  Fatal error: Call to a member function difference() on string in

What is wrong in my code?


texts:
What is the easiest way to view current $form_state variables while working with #ajax?
Is there a way I can get dpm() to update automatically on each AJAX load?
If it matters, I'm testing AJAX on a Node Submit form.


texts:
After a lot of mysql tunings, I intend to use Varnish as the last resort to improve my D6 site's performance which has become increasingly sluggish. I realized that Varnish will not work with D6. And due to lack of som contrib modules, I still can not migrate to Drupal 7 which, as I understand, makes migration to Pressflow pretty redundant.

I am using nginx + php-fpm as web server and try to avoid Apache at any cost. This approach has of course its downside, for example I could not make use of Boost module. Now my question is that whether pressflow works with my web server configuration? and whether migration is a good idea performance-wise? And Pressflow suites me, where can I find docs to make a smooth migration on Ubuntu server.

Thanks for your suggestions.


texts: How is it possible for users to submit a node without a required image field?

texts:
I am using Drupal 7 and I have defined a custom content type, Picture, which has only one required field, an image field.  I am using the default core image field with the Manual Crop module.  The number of images to be added is limited to one.  The field is marked as required.

If it matters, the title is not required because it is automatically generated by the Automatic Node Titles module.

I created this content type to allow users to upload their pictures to the site.  However, sometimes users are somehow able to create nodes of this content type that do not have any image file attached.  Since the image field is marked as required, I do not understand how Drupal can permit the creation of the node without such a file attached.  However, when I click edit, there is no file in the image file dialog box.

I have tried to debug this problem, but I am unable to create a node without an image file myself.  What kind of situation can cause this problem, or how can I debug it?


texts:
I created a template to customize the image field of my view, but I see no change to its output. Can you help me ? thank you

I have to clear the cache of my website.


texts:
I am in the process of optimizing my Drupal site by removing unnecessary css files.

Running an audit I have found that /misc/ui/jquery.ui.core.css, /misc/ui/jquery.ui.theme.css and /misc/ui/jquery.ui.slider.css are relatively large but are never called.

I have tried removing them in my template.php file with the following but they still remain. How can I unset them?

unset($css[DRUPAL_ROOT.'/misc/ui/jquery.ui.slider.css']);
unset($css[DRUPAL_ROOT.'/misc/ui/jquery.ui.core.css']);
unset($css[DRUPAL_ROOT.'/misc/ui/jquery.ui.theme.css']);


texts:
I am currently running Drush 7 and its working fine for D7.

But I want to run it for D8 site. I have also seen many post where it is mentioned that Drush 7 support D8 but its not true.

So i am trying to install Drush 8.

Try to run below command

composer global require drush/drush:8.*

Or

composer require drush/drush:dev-master

./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
      - Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
      - drush/drush dev-master requires consolidation/robo dev-master -> satisfiable by consolidation/robo[dev-master] but these conflict with
  your requirements o r minimum-stability. Installation failed, deleting
  ./composer.json.

But unable to get success. Any suggestion how achieve this?


texts:
I want my user to create content in which he can select a creator (in a select list) of products displayed on his article.
If he selects an existing creator during creation of the article, the publised article has to display the name of this creator + information about the creator (website + adress + maybe more). That means I have to enter this information into X fields for each creators.

If my user wants to add a new creator in this select list, he can do it directly when he creates his article. He enters the name of the creator + link to website + adress

My problem is that I don't know how to do it.

I've tried with that :
*new taxonomy + 2 Link fields added fopr this taxonomy

But how can I enter the content of these fields linked to the taxonomy ? How can I allow my user to add content on new creators he wants to add ?


texts: Separate urls for child node with multiple parent nodes?

texts:
I have a question. I am currently building a site with different sections (a content type with childrens of type normal-content), where some content is identical on parts of the site but some pages have their own version of the page. Se example below

section1/about_us (nid 45)
section2/about_us (nid 45)
section3/about_us (nid 62)
section4/about_us (nid 45)

The issue in my example is that when using pathauto to create the urls the url and the hierarchy is created correctly but only one of the nodes is treated as a parent in regards of the url. They all get the same url section1/about_us (except the one that is created separately). Which I think is the correct way to create the urls but in my case I need separate urls even if the page loaded is the same since it reflects a virtual hierarchy. Is there a way for me to hook into some function to let the pathauto create separate urls for each section?

Best regards,
Jocke


texts: How to add css class to local action menu item created with page manager variant 301 redirect?

texts:
I add some local action links with Page Manager using HTTP response code variant of type 301 redirect.
Anybody knows a way to add a unique class to such a link?


texts:
Can we call submit handler of one form into another form?

I have two forms say user profile form and  choose membership plan I want to unset submit function of choose membership plan and want to show in user profile form and also both forms field must save.

like  multi-step form.

 function myform_form_alter(&$form, &$form_state, $form_id) {
   if($form_id === "ms_membership_list_memberships_form") {
     $form['#validate'][] = "_myform_form_submit_handler";
   }
   if($form_id === "user_profile_form") {
     $form['#validate'][] = "_myform_form2_submit_handler";
   }
 }

 function _myform_form_submit_handler($form, &$form_state) {
   $form_state['rebuild'] = TRUE;
   $form_state['redirect'] = '/user/1/edit';
 }

 function _myform_form2_submit_handler($form, &$form_state) {
   $form_state['rebuild'] = TRUE;
   $form_state['redirect'] = '/ms/checkout';
 }


texts: Use drush to put a site in maintenance mode

texts:
drush @mysite cget system.maintenance shows:

  message: '@mysite is currently under maintenance. We should be back shortly. Thank you for your patience.'
      langcode: en

Drupal 8 uses state values to record transient state, so drush @mysite sget system.maintenance_mode gives me a 1 or a 0.

But, try as I may, I cannot see how to set the boolean. I've tried:

$ drush @mysite sset system.maintenance.mode "TRUE" --format=boolean
$ drush @mysite sget system.maintenance_mode
0
$ drush @mysite sset system.maintenance.mode "TRUE" --format=auto
$ drush @mysite sget system.maintenance_mode
0
$ drush @mysite sset system.maintenance.mode true --format=auto
$ drush @mysite sget system.maintenance_mode
0
$ drush @mysite sset system.maintenance.mode true --format=boolean
$ drush @mysite sget system.maintenance_mode
0

What's the secret?


texts: How can I display custom data from the database in a View?

texts:
I'm working to create a new website in Drupal 8 and cannot figure out how to reference custom table data within a View.

Specifically, I have a script that is taking data from an external DB and populating it into my Drupal DB into custom tables. How can I allow Views to see this data?

In Drupal 7 I have experience using the Forena module and the Data and Schema modules to accomplish same DB and external DB references, but what I'm finding is that support for these three modules in Drupal 8 appears to be lacking, making me think that there is a better way to do this in D8 that everyone knows about but me. :)

I'm not sure if I'm just not researching correctly, but I'm unable to find a clear answer about how to go about obtaining this functionality in Drupal 8. Drupal 8 is so different and I'm not sure if I should be looking for a contributed module or if this is something I would code directly.

Hopefully someone can point me in the correct direction?


texts: Avoid admin users editing other admin users

texts:
I'm in a Drupal 7 installation, trying to find a way to avoid admin-users to edit other admin-user's account.

I've created a role for 'content administrators' and this users tasks involve user administration, but I don't want them to be able to edit other content administrators or admin accounts.

I wasn't able to find an option for this or a module providing the functionality and I'm a bit lost about how this can be achieved.

In D6 I guess could use hook_user() to catch an edit and check the target role in order to allow that edit or not, but this hook is gone on D7. The closest thing is hook_user_alter(), but this is called after the edit, so I can't use it.

Any pointers?


texts: How can I return a different number of results per page for a view if a user is accessing the site with a mobile device?

texts:
I have a large number of views that show member profiles.  Right now, I only show 8 members per page, because on a mobile device it takes a very long time to scroll.

However, for the desktop, I could easily show 20 members per page.

Since there are a large number of views, I don't want to do this if I have to duplicate all of them and change the pager settings.  Is there another way to return a different number of results per page if the user is on a mobile device?


texts:
I can understand that hook_menu is for modules only, not custom themes.
But if I want to add custom paths/urls to my theme what should I do?

For example if I want some of the content to load by ajax, and I want to use custom urls, then a "hook_menu" would be great for custom themes.

Surely there must be another solution than to write a small custom module?

Any suggestions and help is appreciated.

Raf


texts:
I want to achieve the following term listing:

clothing (17)

dresses (2)
skirts (3)
tops (12)

accessories (5)

bags (1)
jewelery (4)
necklaces (2)
rings (2)

Is this possible with views? I know you can use the "Taxonomy Term: Content with term" relationship, but this only counts the nodes attached to the parent terms and not those attached to the child terms...


texts: Add a class to a table with ckeditor dialog button

texts:
I'm using ckeditor with the table plugin, which I think comes standard with the ckeditor module. What I want to do is to add a button in the table dialog modal that will then add a class to the table inserted.

I've been playing with this https://www.drupal.org/node/1793710, but I'm not sure how to hook into the dialog box.


texts: How to print the number of nodes of a certain type referencing to content

texts:
Using Drupal 7 and the latest Views and Entity Reference modules.
I have 3 content types:
- Destination
- Museum
- Restaurant

Museum and Restaurant both reference Destination via field_destination through Entity Reference. What I'm trying to do is to pull on each Destination page the number of each (Museums and Restaurants) in a block.
Bear in mind that Destination doesn't directly reference to neither, it only gets referenced in the other 2 content types.
Managed so far to create 2 relationships, one depending on the other, to pull out a sort of 2 ways reference.
Once I can pull out information about one specific content type pointing to Destination, I can use aggregation and set it up. The problem is... I cannot differentiate.

Any suggestions on how to make the difference between the two when they both use the same reference field?


texts: How to adjust position of drop-down block in Nice-Menu?

texts:
I have inherited a site built in Drupal 6 that uses Nice-Menus for both the top and side nav bars.  I've been tasked with modifying the current navigation and have run into issues adjusting both the position and width of various menu items.

You can see the issue by going to http://neoninc.org and hovering over "ABOUT" in the top nav bar, then "About NEON & Mission >>."  You should see that the menu item for "Governance" doesn't align properly with its parent item.

The previous developer added the following items to the CSS page called by nice-menu to adjust their widths:

ul.nice-menu li.menu-563 li { width: 20em; !important}   /*  ABOUT */
ul.nice-menu li.menu-840 li { width: 20em; !important}   /* CONTACT US */
ul.nice-menu li.menu-236 li { width: 24em; !important }  /* SCIENCE */
ul.nice-menu li.menu-4191 li { width: 20em; !important } /* CITIZEN SCIENCE */

I tried adding the following:

ul.nice-menu li.menu-781 li { margin-left: 16px; !important} /*  ABOUT >> Governance */

and then:

ul.nice-menu li.menu-781 li { left: 16px; !important} /*  ABOUT >> Governance */

both of which seem to work when editing the CSS directly in FireBug.  They don't work when inserted into the actual CSS file, and I'm stumped.

Yes, I've rebooted, cleared the local cache, cleared all caches in drupal, and double-checked that I actually uploaded the edited CSS file.

Any suggestions are greatly appreciated!


texts: How can I apply changes to user permissions across several sites?

texts:
I am using Drupal 7, we have a total of 99 different instances of pretty much the same site.  All sites have the user roles of adm_core and mgr_center.

We are currently using drush and puppet to apply changes/updates across sites.

What I'm wondering is if there is a drush command that I can use to just give adm_core the same privileges as mgr_center?

If not does anyone have suggestions on the best method to do this across all sites short of going and changing permissions site-by-site?


texts:
I created an index view "Search API".

I added the flags to the index.

How to display the rendered entity of entities flagged with a Search API view?

Currently only the title is displayed, I want to display the display mode "Teaser".


texts:
When Im using the full html input format. Is there a way I can use some code to print the url of the front page of my site, so If I were to migrate the site it would still work?

I could do this with pathlogic but im wondering if there is a php type value that full html would use?

Thanks


texts: What are configuration entities used for?

texts:
I’m trying to wrap my head around D8 Configuration Entities (CFE).  The concept of a Content Entity (CTE) seems easy – if you want an application that keeps the information for a CD music collection you can build a content entity that creates a table and stores the fields of your CDs (e.g. Artist and Title).

What is a CFE is used for?  When the CFE example in the “examples” module is installed the result is a link to a page that shows a table that contains one default “robot” (Marvin) and a button to "Add A Robot".  How is this different from creating a robot entity via a CTE?

I do appreciate that there is a structural database difference. The data for each robot gets stored in the config table.


texts: Some content is not displaying on one of my Drupal 7 pages

texts:
I inherited a development theme and I am a Drupal newbie. I don't seem to be able to print out any new fields that I add to my content types. I put this code in node.tpl.php:

<?php echo render($content['field_my_text']);?>

I have the corresponding name in my content type. Any ideas on what could be going wrong?

Thanks!


texts:
I'm trying to programmatically create a media file. Here's what I got so far:

$file_data = file_get_contents('http://www.africau.edu/images/default/sample.pdf');

$file = file_save_data($file_data, 'public://3010.pdf', FILE_EXISTS_REPLACE);

$media = Media::create([
  'bundle' => 'file',
  'uid' => '0',
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
]);

$media->setName('Hello')
  ->setPublished(TRUE)
  ->save();

Unfortunately this returns me the following error and the media file doesn't get saved:

  Error: Call to a member function getSource() on null in Drupal\media\Entity\Media->getSource() (line 138 of core/modules/media/src/Entity/Media.php).

What am I doing wrong? How can I fix this error?


texts: Is it possible to set a role specific value for "allow_insecure_uploads?"

texts: I want to override the value for "allow_insecure_uploads" which is in system.file config, but only for specific roles. Am I going to need to do this in a module / does one already exist?


texts: Available options to implement a knowledge base or FAQ repository?

texts:
I just started with Drupal 7 in an enterprise environment. It's running on IIS7 with MySql as the backend.

I'd like to see this Drupal site host a Knowledge Base or FAQ repository. I did some searches for modules and I haven't found any popular solution.

Ideally, as software/product 'issues' arise and solutions are documented, I want the issue and solution to be easily entered and searched by a small (<100) developer and help desk community.

Any suggestions about how to accomplish this? I'm still getting a grasp on the taxonomy, maybe proper use of taxonomy is all thats really needed?


texts: Drupal Commerce custom Coupon Type not discounting

texts:
I'm trying to create my own coupon type so that I can give it a name that will appear in the checkout and add features such as expiry date and product reference. I have been able to add the features to the "percentage amount" coupon type and if I only had one coupon type I'd just change the display name of that, but there will be many coupon types in my shop. Each is a one-time use coupon that a major client can give to their members so there would be types such as Ford-employee-discount and Toyota-employee-discount with individual coupons trackable to individual staff. So even the coupon code wouldn't be good enough to display because it will be something like "F_Emp-JH6d98"

So now that I have a new coupon type I have duplicated all the fields from percentage coupon type but when I get such a coupon added to a bill the "Granted amount" is blank. No discount is applied but the coupon is there on screen and listed as used by the database.

I'd prefer to be able to add a display name field to the coupon type and set it for each coupon I issue (which are made in batches by the Coupon Batch module), but without modifying the Coupon module I can't see how to display the value of that field in the right places.


texts:
I'm looking for an option to override the image-formatter.html.twig template in my own theme. But in the HTML page output (twig debug is set to true) there's no option listed to override the formatter template. The only thing I see is:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- BEGIN OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->

I need to place a rel attribute for the link which surrounds the image.

I found a solution which uses the option that you can write your own field formatter in your own module. But that seems to be too complex for this simple task.


texts: Drupal 7 webform module is not sending email properly

texts:
I have this modules enabled in my Drupal 7 site:

Mail System v7.x-2.34
Mime Mail v7.x-1.0-alpha2
Smtp Authentication v7.x-1.0
Webform v7.x-3.19

I have configured Mail system to "format" mails with MIME Mail and "mail" with SMTP Authentication. This configuration is set as site-wide default class.

It works fine for register user email, but when send mail with webforms it doesn't use that configuration (It sends emails with a local smtp).

How can I make webform take mail system configuration?

This is what I did:

Install smtp module and config to send mails with amazon ese service. (Using the test option of this module it was working fine)
Needed to send html mails so I installed "mime mail" and "mail system" modules
After enable both modules I have created a class with "mail system" module in this way:

Create a class with:

format: MimeMailSystem

mail: SmtpMailSystem
After that apply the new class to:

Site-wide default class

Mime mail module class

Tested the result with post register emails (This was working fine, amazon ses with html emails)
Installed "webform" module and create a contact form
Webform is sending mails but is not using my smtp config, it's using my local sendmail server (I realize this when the email was detected as possible phishing and looked at the email header)
This shouldn't be working like this, it should be using the site-wide default class defined in "mail system"
Post register emails are still working


texts: Additional tab in custom module's admin configuration page

texts:
Can't figure out why two admin pages of my custom module are not showing in different tabs. I've disabled and re-enabled the module, cleared cache, however while both pages are accessible and I see the "Leads" link in the menu, unfortunately they are not aligned into tabs. Can anyone help me to get my tabs?

/**
 * Implementation of hook_menu().
 */

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

  $items['admin/commerce/leads'] = array(
    'title' => 'Leads',
    'access arguments' => array('administer leads'),
    'page callback' => 'leads_active',
  );
  $items['admin/commerce/leads/subscribed'] = array(
    'title' => 'Subscribed Leads',
    'page callback' => 'leads_subscribed',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  return $items;
}


texts: Obfuscation or e-mail spam protection for content displayed through Views module

texts:
Currently, SpamSpan seems to work well for anything outside of Views. Having a hard time finding a solution for e-mails that are displayed through the Views module.

Any help would be very much appreciated.


texts: Drupal Multisite (subdomain) Not Working

texts:
Drupal 6, default installation, default .htaccess, default http.conf for Apache.

sites/ directory looked like this:

all
default
subdomain1.maindomain.com

default site and subdomain1 working well.

Added a new directory, subdomain2.maindomain.com. It has the same ownership and permissions as subdomain1.maindomain.com. It contains default.settings.php, the out-of-the-box one, and settings.php, which is a copy of default.settings.php. The permissions and ownership of the two files are correct.

The 'sites' directory now looks like this:

all
default
subdomain1.maindomain.com
subdomain2.maindomain.com

Visiting subdomain2.maindomain.com returns an error. Visiting subdomain2.maindomain.com/install.php returns an error. I can download an example file from  maindomain.com/sites/subdomain2.maindomain.com/files/example.txt when it is located at /sites/subdomain2.maindomain.com/files/example.txt.

Basically, I've followed all the steps in the docs, and I'm unable to create another 'subsite' accessible from a new subdomain. What am I doing wrong? What else should I be doing?


texts:
How can I remove or rewrite "group/node" and "og_user_node" from url when user click on OG subscribe link ?

siteURL/group/node/63/subscribe/og_user_node

Is there any module like pathauto where I can use to make this url a custom look?

Thanks.


texts: Panels to do a specific layout for one content type edit mode

texts:
How can i use panels to do a specific layout for a content type only for the add and edit form ?
I'm a newbie on panels but not on Drupal.I'm using panels 3 on D7.
will be great to give me examples or tutos ..

thanks


texts: Using Rules to publish nodes depeding value in Field

texts:
I have been trying to figure out how to publish multiple nodes using Rules.

I have content type Parent and content type Child. When Parent is published then Child will be created/published too. This is what I have managed to do with Rules right now.

But now I have created field (list integer) to Parent. Choosing from list (value from 1-9) example value 4. Then Rules should create 4 Child nodes.

This does not work. It creates Child nodes randomly. Example choosing 9 from list it creates just one Child. And sometimes when choosing 4 from list it creates 2 Child nodes.

Apparently there is something that I dont figure out. What would it be? Any help would be appreciated.

Here is what I have in Rules right now:

  Rule to publish Child nodes when Parent is published

  Event:

  After saving new content

  Conditions:

  Content is type of. Parameter: Content: [node], Content types: Parent

  Actions:

  Fetch entity by property. Parameter: Entity type: Node, Property:
  Choose how many Childs, Value: [node:field-number-of-childs] Provides
  variables: Number of Childs (number_of_childs)
  Loop. Parameter: List: [number_of_childs]
  List item: Current list item (list_item)

  Create a new entity. Parameter: Entity type: Node, Content type: Child, Title: [node:nid], Author: [node:author]
  Provides variables: Created entity (entity_created)
  Save entity Parameter: Entity: [entity-created], Force saving
  immediately: true

Any help with this? Thanks!


texts: Fatal error: Class 'Browser' not found : After Updating drupal 6.20 to 6.26

texts:
As i am update my durpal version 6.20 to 6.26 and it gives these error after updating.

   1) Fatal error: Class 'Browser' not found in /opt/lampp/htdocs/mydrupal/includes/common.inc(1731) : eval()'d code on line 4

   2) warning: include(Browser.php) [function.include]: failed to open stream: No such file or directory in /opt/lampp/htdocs//opt/lampp/htdocs/uls/includes/mydrupal/includes/common.inc(1731) : eval()'d code on line 3.

I checked the common.inc file and there is no code for "including browser.php"


texts: Is there any way to connect to a second (MySQL) database in a Kernel Base test?

texts:
Right now I have configured this environment variable in my phpunit.xml to connect to a Drupal database in a SQLite file:

<env name="SIMPLETEST_DB" value="sqlite://localhost//Users/jepster/Dev/my-project/project/docroot/sites/default/files/db.sqlite"/>

This works fine. But can I also connect to a second database like I am doing in the settings.php?

$databases['second-database']['default'] = array(
  'database' => 'second-database',
  'username' => 'second-database',
  'password' => 'second-database',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

Currently my Kernel Base Test fails with the following error:

  The specified database connection is not defined: second-database

That's because I want to connect to my database from a service constructor:

  public function __construct() {
    $this->database = Database::getConnection('default','second-database');
  }

I have been digging in the Drupal core Kernel Base Tests ("core" folder), but I could not find a way there.


texts:
I have a form that was created using Webform 7.x-4.0-rc3. The completed form submits successfully, form values are stored correctly, notification emails are generated, and the confirmation page is displayed.

I want to ensure that only CAS-authenticated users can access this form. With CAS 7.x-1.4 installed on my site, I've updated the CAS configuration and added the form page's URL to the "Require CAS login for specific pages" list. Redirection to CAS and CAS authentication work as expected.

However, the completed form will not submit for a CAS-authenticated user. By dumping $form_state during the execution of drupal_build_form(), I can see that after the user completes the form and submits, $form_state contains none of the values of the completed form and drupal_build_form() treats it as a newly loaded form.

Somehow the interaction with the CAS server when the authenticated user submits is causing the form to be reinitialized, but I don't know where/how.

Anyone have suggestions for how to attack this? Thanks in advance....


texts:
I have a view which has 2 displays :

List : Which is a unformatted list that contains a page
Table : Displays the nodes titles in a table.

What i need is to make the title in each row of the second display redirect to the corresponding node in the first display, regardless of the "item per page" and sorting.


texts:
I am currently getting an error when trying to connect Drupal 8 with Salesforce. This will be the first time I am hooking into Salesforce from Drupal and I am not entirely sure what I am doing wrong. I am using the Salesforce Suite Module.
I get the following errors while creating a new authentication provider? (Not on a local environment so Salesforce can see the URL.)

Notice: Undefined property: Drupal\salesforce_jwt\Plugin\SalesforceAuthProvider\SalesforceJWTPlugin::$credentials in Drupal\salesforce\SalesforceAuthProviderPluginBase->getCredentials() (line 194 of modules/contrib/salesforce/src/SalesforceAuthProviderPluginBase.php).

Warning: openssl_sign(): supplied key param cannot be coerced into a private key in Firebase\JWT\JWT::sign() (line 209 of /home/client-name/vendor/firebase/php-jwt/src/JWT.php).

OpenSSL unable to sign data

Does anyone know where I could start looking or can provide insight into what these errors mean? I have been stuck on this a few days and I can't seem to find anything helpful yet in my research.
The undefined property makes me think that I may be missing a dependency; however, this is a complete guess.
Thank you in advance.


texts: How to remove id="node-[nid]" with Display Suite?

texts:
How I can remove the node id when I override a node layout with Display Suite?

In some (old) how-to I noticed that the id node is not present when a node layout is overridden with DS.

i.e.: from this

to this

Thanks


texts: Webform send emails based on selection criteria

texts:
I am attempting to create a sort of booking / quote form using Webform.

I have 2 taxonomy selection criteria "Location" and "Service", I am trying to get the form to send emails to the users that have nodes in both the matching criteria.

For example, if the selection was Perth, Western Australia and Electrician, I would like the form to send an email to all the users who have nodes created in that criteria.

Hopefully this makes sense, and hopefully it's possible!

I looked at the Rules module; obviously I would use After a webform has been submitted as action. I wonder which actions would help. If I use Send mail to user would adding the Content has term as condition help in sending the form details to the correct user(s)?


texts: Drupal 7 node reference field formatter for nid

texts:
I'm working in Drupal 7 and using the reference module to attach an node reference to another node. I'm then using views to show some of that nodes fields. When I display the field for the node reference, I'm give the choice of formatting it as a title, title with link, or rendering out the whole node. All I really want to be able to do is render out the nid or the node rather than the title. There were a number of modules that did this in Drupal 6, anyone know how to do it in Drupal 7?

Thanks


texts: I can't figure out the difference/relationship between menus and menus

texts:
One of those fundamentals I skipped over because it gave me a headache to think about thinking about it:

Can someone explain, (or point me to documentation that can explain, and won't make me want to punch myself), the difference, the logic, relationships and/or whatever for "menus" (seemingly misnamed collection of page markers the things you make with HOOK_menu) versus "menus" (thingees that you click on to make events happen the things you make with menu_save())?

...bonus points if you can tell me why in the name of all things holy are log-in, log-out, register, my account, and hell, even "switch back" not built into a single core menu block so that I could continue to live in blissful ignorance...


texts:
I use Webform with Commerce product skus field. Now I have a rule to send out an email to customer if webform is submitted. That works fine. But I would like to set a rule to send the email when the customer check out. My problem is that i don't know the token which I have to set in this Drupal Commerce rule. In Webform rule, I use this [data:e_mail-value], but in the Drupal Commerce rule I have [commerce-order:mail] which is not the same, is it?

How can I forward the right user email address from webform submission to the final Drupal Commerce confirmation email?


texts: Form validation: text has to be a number

texts:
I have a textfield in a form that must contain a number. Using an integer for the field type is not possible - it must be text; however, I need to ensure that the input is actually a number. I've used:

function myfunc_form_user_register_form_validate($form, &$form_state) {
  if (!is_numeric($form_state['values']['number'])) {
    form_set_error('number', t('Field must be Numeric'));
  }
}

However, it does not work, that is, no errors are ever displayed. I have implemented the above code in template.php. I know there are Form Validation modules; however, I would like to do such a simple thing myself. I also think it's a bit overkill to create a whole module to simply validate a single field in a single form! I also wonder how to find the $form[] keys. I named the input field number so I imagine that's the key but it's just a guess. I've looked through the Form API and it is not very clear what I am supposed to do. Simple things, such as finding out what's even in $form[] alludes me and it doesn't seem to be clearly explained.


texts: How to set up content writers to produce articles in their own languages

texts:
After spending hours on the Entity Translation and Fields modules I still can't configure a Drupal site, how do I achieve this:

When a content writer logs in and create a node and drops down to their language, it automatically puts their country prefix in front of it: th/this-is-my-article. Currently it allows the drop down, but when created seems to be in English

Tried this through path auto, doesn't let me add the 'th' bit on

Translate all nodes automatically - surely I don't have to physically click each node after I've created it to add another language? This cannot be correct?

Any help welcome.


texts: How to disable Webform form element validation without removing required flag?

texts:
I inherited a website which contains a Webform made form to which I was asked to make some modifications.

The form contains two drop-down selection lists, one with predefined options, one who's content is dynamically filled in by making a request to a web-service based on the selected value of the first drop-down list.

Filling the second drop-down list is not the problem, but since it's marked as required this means that the form is also validated and that's where the error pops up: An illegal choice has been detected. Please contact the site administrator.

Now, since the content of the drop-down is dynamically generated the error itself makes sense as the selected value is compared to the available options. I want to disable the validation without removing the required flag from the form element.

I tried modifying the element options both via hook_form_alter() and a custom validate function, various combinations and I can see that the variable is set and contains the value, yet it is still validated.

$form['submitted']['ss_function']['#needs_validation'] = FALSE;
$form['submitted']['ss_function']['#webform_validated'] = TRUE;

How can I disable the actual form validation without removing the required flag from a Webform form?


texts: How to save the image of a node to the custom directory programmatically?

texts:
I have a cck image field and I have the "uploads" directory in the files folder.

I want the images of these nodes are saved to the directory with the name of the node id and then the image file. Suppose if the node id is 4 then the image should be saved to the following directory.

files/uploads/4/filename

the directory with the name of "4" should be created programmatically.

Which hook should I use for this and how to achieve this? Any one who have some idea?


texts: How to edit and delete drupal 8 custom block content?

texts:
I am not getting any option to edit my custom block body content and not able to delete also.

Please suggest me.

Thanks


texts: How to use another php version for drush 9?

texts:
On live server I use differents drush and php versions for drupal 8.4 and 7.
I install drush 9 to ~/drush9 directory with composer require drush/drush:9.* command.

On dev server and drupal 8.4 I use site.alias.yml file for drush 9:

live:
  host: hostingexample.com
  user: user
  root: /home/user/example.com/public_html/
  uri: http://example.com/
  paths:
    drush-script: '/opt/php70/bin/php /home/user/drush9/vendor/bin/drush'

And for command drush @site.live ev 'print PHP_VERSION' have an error: bash: /opt/php70/bin/php /home/user/drush9/vendor/bin/drush: No such file or directory

If I add

alias php=/opt/php70/bin/php
alias drush9=~/drush9/vendor/bin/drush

in hosting .bash_profile and change drush-script: '/home/user/drush9/vendor/bin/drush' in site.alias.yml. And have an error PHP Parse error:  syntax error, unexpected '[' in /home/user/drush9/vendor/drush/drush/src/Config/Environment.php on line 98. Because on hosting default php version is 5.3.

How to use another php version for hosting and config it for drush 9 aliases?


texts: How can I upload an image in a custom form and save the result in a custom database table?

texts:
I have a custom form and I want to store the values in a custom database table. After submitting the form, the first_name and email_address fields are successfully saved to the database, but image field (file below) is not saving correctly. When I load the values from the database, the file field shows an empty array. Furthermore, checking the database table shows a value of NULL stored in the field.

How do I upload an image through a custom form and save the resulting file id in the database?

Below is my custom form class.

namespace Drupal\my_block_example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;
use Drupal\file\Entity\File;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

class WorkForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'my_block_example_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['first_name'] = array(
      '#type' => 'textfield',
      '#title' => t('First Name:'),
      '#pattern' => '[A-Za-z]+',
      '#required' => TRUE,
    );

    $form['email_address'] = array(
      '#type' => 'email',
      '#title' => $this->t('Email:'),
      '#pattern' => '[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$',
      '#required' => TRUE,
    );

    $form['file'] = array(
      '#type' => 'managed_file',
      '#name' => 'file',
      '#fid'  => 'fid',
      '#title' => t('Logo'),
      '#description' => t('Upload a logo.'),
      '#upload_location' => 'public://',
    );

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

    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $conn = Database::getConnection();
    $file = $form_state->getValue('file');

    if (!empty($file)) {
      $file = \Drupal\file\Entity\File::load($file);
      $file->setPermanent();
      $file->save();
    }

    $conn->insert('employ')->fields(array(
      'first_name' => $form_state->getValue('first_name'),
      'email' => $form_state->getValue('email_address'),
    ))->execute();

    $form_state->setRedirect('entity.node.canonical', ['node' => 2]);
  }
}


texts: When altering the submit button, the form does not work

texts:
We need a <button> instead of an input in our search-form. So I changed the markup accordingly using theme_form_alter:

function giga_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#size'] = 40;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
    $form['actions']['submit'] = array(
      '#type'   => 'markup',
      '#prefix' => '<button type="submit" class="btn btn-primary">',
      '#suffix' => '</button>',
      '#markup' => '<i class="icon-search icon-white"></i>'
    );
    $form['actions']['submit']['#executes_submit_callback'] = true;
    $form['actions']['#type'] = 'none';
    $form['#attributes']['class'][] = 'search-quick';

    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
  }
}

However, I can submit the form, but the search won't be processed. The page reloads and I'm not redirect to the search results. However when I remove $form['actions']['submit'] = array([…]); it all works fine.

I'm not quite sure what's going on here.


texts: Autocomplete adds [nid:] to node references

texts:
I am using the References module for my content types. There are two content types: A and B. Nodes of one type have a reference to nodes of the other type.

I have a node titled ABC and I want to refer it in another node; the autocomplete in the reference field returns me ABC[nid:5] while I want just to have ABC.

How can I resolve this in simple way? Do I need another module?

Note there are nodes with the same title.

The autocomplete function used by the module is the following one.

/**
 * Menu callback for the autocomplete results.
 */
function node_reference_autocomplete($entity_type, $bundle, $field_name, $string = '') {
  $instance = field_info_instance($entity_type, $field_name, $bundle);
  $field = field_info_field($field_name);

  $options = array(
    'string' => $string,
    'match' => $instance['widget']['settings']['autocomplete_match'],
    'limit' => 10,
  );
  $references = node_reference_potential_references($field, $options);

  $matches = array();
  foreach ($references as $id => $row) {
    // Markup is fine in autocompletion results (might happen when rendered
    // through Views) but we want to remove hyperlinks.
    $suggestion = preg_replace('/<a href="([^<]*)">([^<]*)<\/a>/', '$2', $row['rendered']);
    // Add a class wrapper for a few required CSS overrides.
    $matches[$row['title'] . " [nid:$id]"] = '
' . $suggestion . '
';
  }

  drupal_json_output($matches);
}


texts:
When you click on a search result, you navigate to that node or user. I would like to show the search results in a block when a user navigates to one of the search results, so the other results are always quickly available. Any idea if this is possible?

I was thinking... Make search result variable ($search_results) global, and show this in a php block. But maybe there are better ways to solve this issue?


texts: How can i add edit profile link dynamically?

texts: I have change the default user account page url to cms/dashboard and its redirect to custom page where edit profile link is not available. So i want to add the custom edit link, i add the block image and add the link to that image which is cms/[account:uid]/edit but its converting like cms/%5Baccount%3Auid%5D/edit. Is there any other way to add the Edit Profile link so that user can access the default edit page and change the profile information.


texts: I'm using the Node Field module. When I translate a node its respective node fields are not copied to the translation, forcing me to recreate them by hand. Is there a workaround to this?


texts: How can I see a log of emails that Drupal has sent?

texts: How can I see a log of emails that Drupal 7 has sent? It would be handy for things like troubleshooting registration issues... to see that registration emails are actually being sent.


texts: Hybridauth not working fine when rule configured with domain and sub-domain page

texts:
I have configured Hybridauth social media module for my drupal. I have one main domain and sub-domain configured with my website. I have configured some rule for redirecting to home page with some conditions.

With that, For login, I have configured hybridauth for google and Facebook. In both the login process, The behavior is same, Once i enter credentials of facebook or google account, It shows me Closing.... message, If i remove Url parameter, It shows me logged in page of my drupal site.

Please help me to solve out this problem. Thank you in advance.