gebeer

Processing fields for multi language forms

Recommended Posts

Hello,

I am building a dynamic frontend form from fields of a page, following Soma's great gist example.

The form is working fine, except for multi language values.

After this part of the code

$form->processInput($this->input->post)

when I loop over the form fields, I don't know how to access the multi language values of a field

foreach($form as $field) {
    // how to get multi lang values here
}

What I tried is not working

        foreach($form as $field) {
        	if($field->type instanceof FieldtypeLanguageInterface) {
        		foreach ($languages as $lang) {
        			$langval = $editpage->$field->getLanguageValue($lang);
        			$editpage->$field->setLanguageValue($lang, $langval);
        		}
        	} else {
	            $editpage->set($field->name, $field->value);
        	}
        } 

Actually the $field->type returns just "text" for a PageTitleLanguage field.

var_dumping the $field reveals that the language values are stored deep inside the object like

      'value1023' => string 'Testworkshop2' (length=13)
      'value1032' => string 'Testworkshop2 Englisch' (length=22)

So how would I access those other than pulling them directly from $this->input->post?

Share this post


Link to post
Share on other sites

I think the problem is with $form->processInput($this->input->post) not taking into account multilanguage values.

get_class($editpage->title) returns: LanguagesPageFieldValue

But inside the foreach($form as $field) {...} a var_dump(get_class($field)) for the title field returns: InputfieldPageTitle

These are 2 different types of objects. I would expect to get a LanguagesPageFieldValue object where I can access multi language values. But sadly this is not the case.

Would be nice to have a method like processInputLanguage().

I have searched the code and the forum but cannot find a clue how to deal with multiliangugae fields in form processing.

Any help would be much appreciated.

Share this post


Link to post
Share on other sites

The docs says:

$page->of(false); // outputFormatting must be OFF

https://processwire.com/api/multi-language-support/multi-language-fields/#getting-and-setting

"The value of a multi-language or language-alternate field is affected by the "outputFormatting" setting of a page. On the front-end of your site, outputFormatting is always turned on, unless you've turned it off."

"When outputFormatting is ON, the value of a multi-language field is a string (as it shows in most examples on this page). That string reflects the value from the current user's language. If the value is blank in the current user's language, the value from the default language will be there instead.

However, when outputFormatting is OFF, the value of a multi-language field (like $page->body) will instead return an object of type LanguagesPageFieldValue, rather than a string. That object contains all of the translations available for the given field."
 

I'm not sure that this solves anything, I'm just guessing. Sorry if I'm mistaken.

  • Like 3

Share this post


Link to post
Share on other sites

Thank you for taking the time to look into this.

Unfortunatley this doesn't apply to my situation because I already switch off output formatting right before the foreach loop

        $editpage->setOutputFormatting(false);
        foreach($form as $field) {
            // here is where I need to get the multi language values
            $editpage->set($field->name, $field->value);
        }
  • Like 1

Share this post


Link to post
Share on other sites

Raising this from the dead, but setLanguageValue() and getLanguageValue() are pretty useful for those kind of things.

From code/Page.php
 
 * Methods added by LanguageSupport.module (not installed by default) 
 * ------------------------------------------------------------------
 * @method Page setLanguageValue($language, $fieldName, $value) Set value for field in language (requires LanguageSupport module). $language may be ID, language name or Language object.
 * @method Page getLanguageValue($language, $fieldName) Get value for field in language (requires LanguageSupport module). $language may be ID, language name or Language object. 
 *
  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By bobbit6k
      Hi guys, 
       
      is there a way to declare numbers other than integer and float?
       
      My issue is that intgere is not enough for me because i'm dealing with multiple of bilions (let's say something like 111,532,372,567)
       
      Thanks,
       
      Rob
    • By zaib
      I'm fetching results from a template which works fine but when i change the language (in my case changed language is ARABIC), its showing me nothing
      $getResult = $pages->find("template=t3Cities_list, tags={$page->title}"); where "tags" are checkboxes with multi selection, How i can match the values?
    • By cleanboy
      Hey all,
      Mods; please feel free to move this if it is in the incorrect place although I thought this was the best place for it.
      Kinda new to processwire but getting the hang of it....I am trying to build a payment form with the Stripe platform but failing miserably....I really hope someone can help!
      So I am building my form with the PW API and also following through this documentation here: https://stripe.com/docs/elements and here: https://stripe.com/docs/charges
      My form is pretty basic just for testing purposes right now:
      <form id="payment-form" class="pusher" name="payment-form" method="post" action="./#booking-form"> <?php $tokenName = $this->session->CSRF->getTokenName(); $tokenValue = $this->session->CSRF->getTokenValue(); echo '<input type="hidden" id="_post_token" name="' . $tokenName . '" value="' . $tokenValue . '"/>'; $out = ""; $out .= '<div id="card-number"></div> <div id="card-errors"></div>'; // create a new form field (also field wrapper) $form = $modules->get("InputfieldForm"); $form->action = "./"; $form->method = "post"; $form->attr("id+name",'payment-form'); // First Name $field = $modules->get("InputfieldText"); $field->skipLabel = true; $field->attr('id+name','name'); $field->attr('placeholder','Full Name'); $field->required = 1; $form->append($field); // append the field to the form // create email field $field = $modules->get("InputfieldEmail"); $field->attr('id+name','email'); $field->attr('placeholder','Email'); $field->required = 1; $form->append($field); // append the field // oh a submit button! $submit = $modules->get("InputfieldSubmit"); $submit->attr("value","SUBMIT"); $submit->attr("id+name","submit"); $submit->attr("class","cta white"); $form->append($submit); if($input->post->submit) { // user submitted the form, process it and check for errors $form->processInput($input->post); if($form->getErrors()) { // the form is processed and populated // but contains errors $out .= $form->render(); } else { foreach($input->post as $key => $value) echo htmlentities("$key = $value") . "<br />"; } } else { foreach($form->children as $input){ $out .= "<div class='col-sm-6'>{$input->render()}</div>"; } } echo $out; ?> </form> That alone works fine and returns all of the fields values after I click submit which is great...now we add the javascript:
      //Stripe var stripe = Stripe('pk_test_*****************'); var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. var style = { base: { // Add your base input styles here. For example: fontSize: '16px', lineHeight: '24px' } }; // Create an instance of the card Element var card = elements.create('card', {style: style}); // Add an instance of the card Element into the `card-element` <div> card.mount('#card-number'); card.addEventListener('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); // Create a token or display an error when the form is submitted. var form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createToken(card).then(function(result) { if (result.error) { // Inform the user if there was an error var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { // Send the token to your server stripeTokenHandler(result.token); } }); }); function stripeTokenHandler(token) { // Insert the token ID into the form so it gets submitted to the server var form = document.getElementById('payment-form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit(); } This gives an error in the console: Uncaught (in promise) TypeError: form.submit is not a function. 
      This is because our submit input has the name "submit". Ok thats cool...I can change that but once I do the page essentially refreshes and the form just shows again and it doesnt give me the values it did before....I guess it isnt posting? either way after I submit the form after changing the name of the submit button the form just loads again and anything inside: if($input->post->submit) doesnt seem to execute...so what gives?
      If anybody here has done this before with PW 3+ I would really love an example of how to use this to the point of sending information to Stripe.
      I have installed Stripe with composer and it would appear that I can refer to it in Processwire just fine...my problem is just getting to the point where I need to refer to it which is after the submit.
      I have seen the PaymentStripe module but tbh the documentation on that is somewhat lacking and im not even sure it works with the latest version of stripe? Im also not sure how to integrate that into a form either unless you use something along the lines of the example code provided after the form has been submitted but I cant even seem to submit the form to even try that and im not really sure why.
      Here is the PaymentStripe module page for those wondering: https://modules.processwire.com/modules/payment-stripe/
      Any help would be greatly appreciated!
      Cleanboy
    • By prestoav
      Hi all,
      PW: 3.0.42
      I'm trying to have responsive images in the body field. First I need to stop the image tag generated by CKEditor adding the width attribute to the image tag on insertion. I found the 'Skip width attributes on image tags?' in the settings of ProcessPageEditImage and that suggests it does exactly what I'm after.
      Sadly, even when this checkbox is checked and a new image is inserted the width attribute is still added.
      Am I missing something?
      TIA.

    • By abdus
      Based on this forum post, I wanted to find a more elegant solution for changing a field's settings per template. Hooking the page editor after it generates the form works and may still be needed for more complex modifications. But using field & template context, it's easier to modify the field settings and it greatly reduces the need for creating an almost identical field just to adjust a few things.
      In my blog post, I've written on how to extend contextual options to allow any fieldtype / inputfield settings to be changed depending on the template. Hope you find it useful, and if you have any questions or comments, feel free to post them here.
      https://abdus.co/blog/doing-more-with-fewer-fields-in-processwire/