Jump to content

[SOLVED] Conditional fields based on select option inside renderForm


Recommended Posts

	$some_options = array(
            array(
                'id_option' => 'optone',
                'name' => $this->l('Option 1')
            ),
            array(
                'id_option' => 'opttwo',
                'name' => $this->l('Option 2')
            ),
        );

        $fields_form = array(
            'form' => array(
                'legend' => array(
                    'title' => $this->l('This is the title'),
                    'icon' => 'icon-cogs'
                ),
                'description' => $this->l('Here the description...'),
                'input' => array(
                    array(
                        'type' => 'switch',
                        'is_bool' => true, //retro-compat
                        'label' => $this->l('Enable'),
                        'name' => 'BTN_ENABLE_0',
                        'values' => array(
                            array(
                                'id' => 'active_on',
                                'value' => 1,
                                'label' => $this->l('Enabled')
                            ),
                            array(
                                'id' => 'active_off',
                                'value' => 0,
                                'label' => $this->l('Disabled')
                            )
                        ),
                    ),
                    array(
                        'type' => 'select',
                        'lang' => true,
                        'label' => $this->l('Select an Option'),
                        'name' => 'SELECT_OPT',
                        'desc' => $this->l('Just select the option...'),
                        'options' => array(
                            'query' => $some_options,
                            'id' => 'id_option',
                            'name' => 'name'
                        )
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Username'),
                        'name' => 'USERNAME',
                        'suffix' => 'USER',
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Password'),
                        'name' => 'PASSWORD',
                        'suffix' => 'SECRET',
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Some Code'),
                        'name' => 'SOME_CODE',
                        'suffix' => 'CODE',
                    ),
                    array(
                        'type' => 'desc',
                        'name' => '',
                        'text' => $this->l('And here another random text or whatever...')
                    ),
                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                    'class' => 'btn btn-default pull-right'
                )
            ),
        );

So I have this code and I want to show "Username" and "Password" fields only when I have "Option 1" selected and hide "Some Code" field.

Then the oposite when "Option 2" is selected. Hide both "Username" and "Password" fields and show "Some Code" field.

And that's it, I've already googled, searched here inside forum and just can't find the answer, which I believe to be something simple.

Thank you very much in advance.

Edited by Pedro Lima
SOLVED (see edit history)
Link to comment
Share on other sites

Hi,

Thank you for your answer.

Yes, it is for a new module I am personally testing but in order to make it work I need to have a selectbox.

I will try to explain in steps, maybe I can be more clear, so let's see:

  1. We get inside that Module configuration page;
  2. We have a selectbox with 2 different options (let's call it Option 1 and Option 2);
  3. I can select one of those two options (the common functionality of any selectbox);
  4. If I select "Option 1", bellow that selectbox it should appear two text fields (I named those fields "Username" and "Password" but those are just text fields);
    1. No other fields should be visible, only these 2;
  5. If I select "Option 2", bellow that selectbox it should appear one field (I named that field "Some Code" and it should be just a text field);
    1. No other fields should be visible, only this 1.

And that's it.

I tried Googling this, I saw that there are modules doing it so it's "duable" and I just wanted to see if the community could help.

If not, I understand that and this thread can be closed and I will not bother the community again with "my problems" (that can be other one problems too). But it's kinda sad because I usually use a lot other platforms and the communities are way more interactive. :(

Link to comment
Share on other sites

Hi Pedro 

You can try to add for example admin.js file and "hook" it into  back office header hook "hookBackOfficeHeader" .

There is js file you could add events that will watch when select is clicked and hide options you do not want to show.

You target select by name :

$(document).ready(function() {

    $(document).on('change', "input[name='SELECT_OPT']", function() {
        if ( contition ) {
        	$('input[name="USERNAME"]').hide()
            $('input[name="PASSWORD"]').hide();
        } else {
        	$('input[name="USERNAME"]').show()
            $('input[name="PASSWORD"]').show();
        }
    });

});

Just example code you probably need bit more code.

 

And it is true that community have maybe less active people but that just mean you have to wait a bit for answer.

You can bump in a week or check if your  original question needs more info, but topic should not be closed and you do not bother anyone.

Also if you do not receive answer on forum and no similar topics and it is connected with code and development you can ask also on https://gitter.im/PrestaShop/General

There usually after day or two developers from PrestaShop Team see question and may give quick response. 

  • Thanks 1
Link to comment
Share on other sites

First, let me thank you @razaro

Then, let me leave a reference for future visitors from what I've been trying during these last days.

After a lot of trial and errors, on my little time for this matter, I now understand that in order to call CSS or JS in backoffice, I should first put this on the "public function install()", right in the end:

return parent::install() && 
$this->registerHook('backOfficeHeader') &&
$this->registerHook('displayBackOfficeHeader');

After that, I can then create a function to use CSS or JS in backoffice, and for that one should do something like so:

public function hookBackOfficeHeader($params)
{
    if (_PS_VERSION_ < '1.5'){
        Tools::addJS(($this->_path).'views/js/custom.js', 'all');
        Tools::addCSS(($this->_path).'views/css/custom.css', 'all');
    }else{
        $this->context->controller->addJquery();
        $this->context->controller->addJS($this->_path.'views/js/custom.js', 'all');
        $this->context->controller->addCSS($this->_path.'views/css/custom.css', 'all');
    }
}

So now back to the topic of my question, starting from your answer.

On 11/11/2019 at 8:39 AM, razaro said:

$(document).ready(function() {

    $(document).on('change', "input[name='SELECT_OPT']", function() {
        if ( contition ) {
        	$('input[name="USERNAME"]').hide()
            $('input[name="PASSWORD"]').hide();
        } else {
        	$('input[name="USERNAME"]').show()
            $('input[name="PASSWORD"]').show();
        }
    });

});

Just example code you probably need bit more code.

It is indeed an example code and I thank you for that because thanks to this, I could start looking for solutions. Not the ones I thought in the first place, but hey it's a start!

Unfortunately, the code like this it would never work, even as example code.

This is my code "working":

$(document).ready(function() {
    var opt = jQuery("#SELECT_OPT").val();
    $("#SELECT_OPT").on('change', function(e) {
        opt = jQuery("#SELECT_OPT").val();
        if ( opt == "optone" ) {
        	$('input[name="USERNAME"]').show()
            $('input[name="PASSWORD"]').show();
        } else {
        	$('input[name="USERNAME"]').hide()
            $('input[name="PASSWORD"]').hide();
        }
    });
});

Problem with this code, specifically for my use case, is that although it works, it does not work as intended. :(

When "Option 1" is selected, fields appear and that's all ok.

optone_selected.jpg

But when "Option 2" is selected, input fields do not appear and that, apparently, should be ok... but it's not! As you can see, labels are still there:

opttwo_selected.jpg

So, conclusion, this is my proper working JS code:

$(document).ready(function() {
    var opt = jQuery("#SELECT_OPT").val();
    $("#SELECT_OPT").on('change', function(e) {
        opt = jQuery("#SELECT_OPT").val();
        if ( opt == "optone" ) {
        	$('input[name="USERNAME"]').parent().parent().parent().show()
            $('input[name="PASSWORD"]').parent().parent().parent().show();
        } else {
        	$('input[name="USERNAME"]').parent().parent().parent().hide()
            $('input[name="PASSWORD"]').parent().parent().parent().hide();
        }
    });
});

And there we go! :)

I just came here to leave my solved case because a lot of times I check questions like mine and then, no solution. Or when it has a solution, it's not clear and it does not help so then we need to scratch the web to find different answers to fill the puzzle.

Well, this is it. See you guys next time and thank you very much once again.

Edited by Pedro Lima
Adjusting images positions (see edit history)
  • Like 1
  • Thanks 1
Link to comment
Share on other sites

  • 8 months later...

Hello,

this is so old, but this can help the people to hide all the row from helper from. 

Only you have to change the input name and the val:

$(document).ready(function() {
		var inputstohide = [ $('input[name="date_start"]'),
							 $('input[name="date_end"]')
							];
		var change =  $('select[name="option"]');
		var valtosearch = 1;
		/*OPTIONAL TO HIDE THE INPUTS AFTER PAGE LOAD*/
		for (var i=0; i<inputstohide.length;i++){
			
				inputstohide[i].closest('.form-group').hide();
		}
       /******************/
		change.on('change', function(e) {
			opt = $(this).val();
			if ( opt == valtosearch ) {
					for (var i=0; i<inputstohide.length;i++)
						inputstohide[i].closest('.form-group').show();
					
			} else {
				for (var i=0; i<inputstohide.length;i++)
						inputstohide[i].closest('.form-group').hide();
					
			}
		});
});

 

Edited by kurungele (see edit history)
Link to comment
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
×
×
  • Create New...