How do I send a command after submitting a form?

I need to do something when the user submits a form so that it sends a command to the server, :

 if($_GET("cmd")=="save")

Got to do something with the thing above,
I thought of using:

<a href="?cmd=save">Save</a>

But if I do that it will not complete the form action so:

<form action="{{ pageName }}">

Will not be executed…
So how would I fix this problem?
thanks all 🙂

javascript – wordpress contact form 7 – redirecting without submitting

There is a wordpress page containing contact form 7 form. Upon submit, it shows the thanks message along with the download doc link.

We want to stop accepting certain email ids such as gmail. For the same we are using following script:

<script>
document.addEventListener( 'wpcf7submit', function( event ) {
    var foo = document.getElementsByName("Email")(0).value;
    var domain = foo.substring(foo.lastIndexOf("@") +1);

    if ( domain == 'gmail.com') {
        
     
    window.location.href = 'https://www.example.com';
    return false;

   
    }
}, false );
</script>

This script is working fine and redirecting ‘gmail’ users to another page, however it shows the thanks message for few seconds and then redirects. We do not want to show the thanks message at all and directly redirect him/her.

May be instead of ‘wpcf7submit’ we need to use some other event as the thanks message comes upon submission.

Any thoughts?

8 – Upload a file by Ajax without submitting the form

This code uploads one file with Ajax, attaching it to an existing node’s file field. The content type is file_test, and the field is field_da_files.

(I’m not a professional programmer, so there are no doubt better ways to do this.)

Here’s some HTML/JS that talks to a Drupal controller. It sends the node id, and the file to be stored.

In uptest.html.twig:

<p>NID <input type="text" id="nid" name="nid"></p>
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">

In library JS file:

(function($, Drupal) {
  Drupal.uptestInitialized = false;
  Drupal.behaviors.uptest = {
    attach: function(context, settings) {
      if (Drupal.uptestInitialized) {
        return;
      }
      Drupal.uptestInitialized = true;
      $(document).ready(function() {
        $("#but_upload").click(function() {
          var fd = new FormData();
          var files = $('#file')(0).files(0);
          if (! files) {
            alert("No files");
            return;
          }
          var nid = $("#nid").val();
          if (! nid) {
            alert("No nid");
            return;
          }
          fd.append('nid', nid);
          fd.append('file', files);

          $.ajax({
            url: '/uptest-save',
            type: 'post',
            data: fd,
            contentType: false,
            processData: false,
            success: function(response){
              let result = response.success;
              if (result){
                alert('yay!');
              }
              else {
                let msg = response.message;
                alert('file not uploaded: ' + msg);
              }
            },
          });
        });
      })
}}})(jQuery, Drupal);

Routing file:

uptest.default_controller_hello:
  path: '/uptest'
  defaults:
    _controller: 'DrupaluptestControllerDefaultController::hello'
    _title: 'uptest'
  requirements:
    _permission: 'access content'

uptest.default_controller_upload:
  path: '/uptest-save'
  defaults:
    _controller: 'DrupaluptestControllerDefaultController::saveFile'
    _title: 'Save'
  requirements:
    _permission: 'access content'

In the controller:

use DrupalCoreControllerControllerBase;
use DrupalCoreFileFileSystemInterface;
use SymfonyComponentDependencyInjectionContainerInterface;
use DrupalCoreEntityEntityTypeManagerInterface;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationRequest;
use DrupalComponentUtilityBytes;

public function hello() {
  $renderable = (
    '#theme' => 'uptest',
    '#cache' => (
      'max-age' => 0,
    ),
    '#attached' => (
      'library' => (
        'uptest/uptest',
      ),
    ),
  );
  return $renderable;
}

public function saveFile(Request $request) {
  $nid = $request->get('nid');
  if (!$nid || !is_numeric($nid) || $nid < 0) {
    return $this->makeUploadErrorResponse('Bad NID format');
  }
  $node = $this->entityTypeManager->getStorage('node')
    ->load($nid);
  if (!$node) {
    return $this->makeUploadErrorResponse('No node with nid of ' . $nid);
  }
  /** @var SymfonyComponentHttpFoundationFileUploadedFile $uploadedFile */
  $uploadedFile = $request->files->get('file');
  if (!$uploadedFile->isValid()) {
    return $this->makeUploadErrorResponse('Invalid file upload.');
  }
  //Get uploaded file metadata.
  $uploadedFileName = $uploadedFile->getClientOriginalName();
  $uploadedFileExtension = $uploadedFile->getClientOriginalExtension();
  $uploadedFileSize = $uploadedFile->getClientSize();
  $uploadedFilePath = $uploadedFile->getPathname();
  //Get node field metadata.
  $nodeFieldMetadata = $this->getFileFieldMetaData('file_test', 'field_da_files');
  if (!$nodeFieldMetadata) {
    return $this->makeUploadErrorResponse('Problem loading file field metadata.');
  }
  //Check uploaded file's extension.
  $allowedExtensions = explode(' ', $nodeFieldMetadata('extensions'));
  if (!in_array($uploadedFileExtension, $allowedExtensions)) {
    return $this->makeUploadErrorResponse('Extension not allowed.');
  }
  //Check the file size.
  $maxSizeAllowed = Bytes::toInt($nodeFieldMetadata('max file size'));
  if ($uploadedFileSize > $maxSizeAllowed) {
    return $this->makeUploadErrorResponse('File too large.');
  }
  //Check cardinality.
  /** @var DrupalfilePluginFieldFieldTypeFileFieldItemList $fieldValueInNode */
  $fieldValueInNode = $node->get('field_da_files');
  $fieldAttachedFileItemList = $fieldValueInNode->getValue();
  $nodeFileFieldNumAttachments = count($fieldAttachedFileItemList);
  $allowedCardinality = $nodeFieldMetadata('cardinality');
  if ($nodeFileFieldNumAttachments >= $allowedCardinality) {
    return $this->makeUploadErrorResponse('Maximum number of files for this node already reached.');
  }
  //OK. Attach the file.
  //Prepare the directory.
  $directory = 'private://' . $nodeFieldMetadata('directory');
  $result = file_prepare_directory($directory, FileSystemInterface::CREATE_DIRECTORY);
  if (!$result) {
    return $this->makeUploadErrorResponse('Error preparing directory.');
  }
  //Read the file's contents.
  $fileData = file_get_contents($uploadedFilePath);
  //Save in right dir, creating a file entity instance.
  $savedFile = file_save_data($fileData,
    $directory . '/' . $uploadedFileName,
    FileSystemInterface::EXISTS_RENAME
  );
  if (!$savedFile) {
    return $this->makeUploadErrorResponse('Error saving file.');
  }
  //Attach to the node.
  $node->field_da_files() = (
    'target_id' => $savedFile->id(),
  );
  $node->save();
  return new JsonResponse((
    'success' => TRUE,
  ));
}

/**
 * Make a response for file upload attempt with an error message.
 *
 * @param string $message The error message.
 *
 * @return SymfonyComponentHttpFoundationJsonResponse Response to return to client.
 */
protected function makeUploadErrorResponse($message) {
  $result = (
    'success' => FALSE,
    'message' => $message,
  );
  return new JsonResponse($result);
}

/**
 * Get metadata for a file field.
 *
 * @param string $contentType Content type with the field.
 * @param string $fieldName Name of the field.
 *
 * @return array|bool Metadata, or false if a problem.
 */
public function getFileFieldMetaData($contentType, $fieldName) {
  if ($contentType === '' || $fieldName === '') {
    return FALSE;
  }
  $entityFieldManager = Drupal::service('entity_field.manager');
  $fields = $entityFieldManager->getFieldDefinitions('node', $contentType);
  if (!$fields || count($fields) === 0) {
    return FALSE;
  }
  //Get file field definition.
  if (!isset($fields($fieldName))) {
    return FALSE;
  }
  /** @var DrupalfieldEntityFieldConfig $fieldDef */
  $fieldDef = $fields($fieldName);
  //Get settings, doesn't include cardinality.
  $directory = $fieldDef->getSetting('file_directory');
  //Resolve tokens.
  /** @var DrupalCoreUtilityToken $tokenService */
  $tokenService = Drupal::service('token');
  $directory = $tokenService->replace($directory);
  $fileExtensions = $fieldDef->getSetting('file_extensions');
  $maxFileSize = $fieldDef->getSetting('max_filesize');
  //Get cardinality.
  /** @var DrupalfieldEntityFieldStorageConfig $fieldStorageDef */
  $fieldStorageDef = $fieldDef->getFieldStorageDefinition();
  $cardinality = $fieldStorageDef->getCardinality();
  //Return results.
  $result = (
    'content type' => $contentType,
    'field' => $fieldName,
    'directory' => $directory,
    'extensions' => $fileExtensions,
    'max file size' => $maxFileSize,
    'cardinality' => $cardinality,
  );
  return $result;
}

Hope that helps.

Submitting to SP List, Input string was not in correct format error JavaScript

I am getting the error, “Input list was not in correct format error”

My sharepoint list has single text fields so i cannot see the problem

function savingsdatick(varid) {
//Get Current Tabs before submission
var allTicksForSave = {};
$(“.thischeck”).each(function () {
allTicksForSave($(this).attr(“id”)) = $(this).is(“:Checked”)
});
console.log(“So…”)
console.log(allTicksForSave)

var Tickbox1 = “Tickbox1”;
var Tickbox2 = “Tickbox2”;
var Tickbox3 = “Tickbox3”;
var Tickbox4 = “Tickbox4”;
var Tickbox5 = “Tickbox5”;
var Tickbox6 = “Tickbox6”;
var Tickbox7 = “Tickbox7”;
var Tickbox8 = “Tickbox8”;
var Tickbox9 = “Tickbox9”;
var Tickbox10 = “Tickbox10”
var Tickbox11 = “Tickbox11”;
var Tickbox12 = “Tickbox12”;
var Tickbox13 = “Tickbox13”;
var Tickbox14 = “Tickbox14”;
var Tickbox15 = “Tickbox15”;
var Tickbox16 = “Tickbox16”;
var Tickbox17 = “Tickbox17”;
var Tickbox18 = “Tickbox18”;
var Tickbox19 = “Tickbox19”;
var Tickbox20 = “Tickbox20”;
var Tickbox21 = “Tickbox21”;
var Tickbox22 = “Tickbox22”;
var Tickbox23 = “Tickbox23”;
var Tickbox24 = “Tickbox24”;
var Tickbox25 = “Tickbox25”;
var Tickbox26 = “Tickbox26”;
var Tickbox27 = “Tickbox27”;
var Tickbox28 = “Tickbox28”;
var Tickbox29 = “Tickbox29”;
var Tickbox30 = “Tickbox30”;

  var varid = localStorage.getItem("projectnewTitle");
  var currentStorm = document.getElementById("dale3").innerHTML;
  var siteUrl = _spPageContextInfo.webServerRelativeUrl;
  var clientContext =  SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('SecurityDesignAssuranceLeft');
  this.oListItem = oList.getItemById(currentStorm)
    if(allTicksForSave.SDALEFTBOX0) oListItem.set_item('Tickbox1', 'True');
    if(allTicksForSave.SDALEFTBOX1) oListItem.set_item('Tickbox2', 'True');
    // if(allTicksForSave.SDALEFTBOX2) oListItem.set_item(Tickbox3, "True")
    // if(allTicksForSave.SDALEFTBOX3) oListItem.set_item(Tickbox4, "True")
    // if(allTicksForSave.SDALEFTBOX4) oListItem.set_item(Tickbox5, "True")
    // if(allTicksForSave.SDALEFTBOX5) oListItem.set_item(Tickbox6, "True")
    // if(allTicksForSave.SDALEFTBOX6) oListItem.set_item(Tickbox7, "True")
    // if(allTicksForSave.SDALEFTBOX7) oListItem.set_item(Tickbox8, "True")
    // if(allTicksForSave.SDALEFTBOX8) oListItem.set_item(Tickbox9, "True")
    // if(allTicksForSave.SDALEFTBOX9) oListItem.set_item(Tickbox10, "True")
    // if(allTicksForSave.SDALEFTBOX10) oListItem.set_item(Tickbox11, "True")
    oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded4), Function.createDelegate(this, this.onQueryFailed4));
function onQuerySucceeded4() {
alert("Hi")

}

function onQueryFailed4(sender, args) {
alert(“Failed” + args.get_message())
}
}

A tool for submitting your website to Google and other search engines Proxies-free

I recently had to develop multiple websites quickly and found it too difficult to log in and send multiple websites to Google. That's why I developed this tool to submit my websites to Google. It also works with Bing.

Note that you should provide the URL of your sitemap, not your domain name.

If you need help or have suggestions for other search engines, let me know below :] :]

I will be submitting videos to high PA video sharing sites by manually submitting them for $ 2

I will manually submit videos to websites with high PA sharing

………………………………………….. …………. Welcome to my video submission gig ……………………….. .. …………………………

Advantages of my appearance?

  • 100% handmade link, Safe & White Hat SEO.
  • Permanent backlinks.
  • Handwork
  • 100% satisfaction
  • Full refund if you can't be satisfied with my work

Examples of my websites:

  • Youtube
  • Flickr
  • Linkedin
  • Vimeo
  • Photobucket
  • Dailymotion
  • my place
  • Facebook
  • Twitter
  • Bloggers etc.

The uniqueness of my service:

  • Work 100% manually
  • Fast delivery
  • 24/7 customer service
  • 100% Google Penguin & Panda Safe
  • High ranked websites
  • Submission sites are combined with the video platform Social and Embed to Web 2.0.
  • Get high DA backlinks with high quality results

Kind regards:

humza5

Is it possible to pre-fill a Google form without submitting data in the query string?

I integrate a (Rails-based) web app into a form created with Google Forms and must be able to fill out the form for the user with information that he can edit and add before sending it.

The normal way to do this is with a link that contains the data in a query string. Some stakeholders are concerned about this approach because query string constraints (which vary by browser) may occur and sensitive information may be displayed when users bookmark the links.

Is there any other way to pre-fill a Google form?

Some options that came to mind:

  • It may be possible to insert a row into a Google spreadsheet using the Google API and then open the form with this data. (Populating the table is of course not a problem, but the next step may not be possible.)
  • Google may also allow POSTing on a Google form to be completed in advance. (I doubt it, but …)
  • or maybe there’s something else that I just didn’t think about because I don’t use Google Apps or APIs enough to bring it to my mind.

Views – How to call rest api in Drupal8 after submitting the form

I have created an internal API call as '/api/v1/user/promotional-emails' This API calls some external APIs and we update the data there. In Postman API works well.

Now I have created a user form as '/user/promotional-emails' This form appears fine, but I need to call the API call I created earlier '/api/v1/user/promotional-emails'. but there is always NULL as the answer.

I tried the following method but it doesn't work. I don't know what to do.

/**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    global $base_url;

    $result1 = $form_state->getValue('option1');
    $result2 = $form_state->getValue('option2');
    $result3 = $form_state->getValue('option3');
    $result4 = $form_state->getValue('option4');

    $json = (
        'headers' => (
          'Content-Type' => 'application/json',
        ),
          'form_params' => (
                  'EmailAddress' => 'test@gmail.com',
                  'EmailOptin' => true,
                  'option1' => $result1,
                  'option2' => $result2,
                  'option3' => $result3,
                  'option4' => $result4
              )
            );
    $options = ('option1' => $result1,'option2' => $result2,'option3' => $result3,'option4' => $result4, 'EmailAddress' => 'test@gmail.com');

Option 1 I tried:

 $url = $base_url . '/api/v1/user/promotional-emails';

     $client = new Client(('verify' => false));

     $rest_response = $client->request('POST', $url, $json);

This also gives NULL

Option 2 I tried

$client = Drupal::service('http_client_factory')->fromOptions(array('verify' => FALSE));
    $request = $client->post($base_url.'/api/v1/user/promotional-emails', $options);
    $response = json_decode($request->getBody());

I also get zero here. Can any body help me with this?

My API caller is like this.

public function unsubscribeEmail(Request $request) {
    // Get post body data in json.
    $requestContent = json_decode($request->getContent(), TRUE);
    // Get token.
    print_r($request); exit;
}

Should an empty optional field be shown in the form overview before submitting?

Hye,

FORM FIELDS

Mandatory field; Name, address, etc.
Two optional fields; Overtime and comments.

FLOW

  • Fill out the form
  • Click on the review form
  • Form changes in review mode (all field fields are gone) only summary and receipt
  • Check and submit

QUESTION

If the optional field is empty, should it still be displayed on the overview page with the data empty with the symbol (-) or should it be removed from the form overview?

If it is removed from the overview, does this mean that users who have a field in all fields have a longer summary than users who do not?

thank you in advance