Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

Thymeleaf doesn't take value from input

I have problem with saving value from nouislider.

Here is my code:

html

<form id="campaignForm" th:object="${campaignForm}" method="post" class="form-horizontal">
    <input type="hidden" th:field="*{id}" />
    <div class="form-group">
        <label class="col-sm-3 control-label">Session lifespan (hours): </label>
            <div class="col-sm-7">
                <div id="basic_slider" th:field="*{sessionLifespan}">                                   
                </div>
            </div>
            <div class="col-sm-2">
                <input class="form-control" id="basic_slider_value" th:value="*{sessionLifespan}"/>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-6">  
                <div class="form-group">
                    <div class="col-sm-9 col-sm-offset-3">
                        <button class="btn btn-primary" type="submit">Save</button>                                                 
                        <a class="btn btn-white" th:href="@{/campaigns}">Cancel</a>                                                  
                    </div>
                </div>
            </div>
        </div>
    </form>

js

var basic_slider = document.getElementById('basic_slider');

noUiSlider.create(basic_slider, {
    start: 0,
    step: 1,
    behaviour: 'tap',
    connect: 'upper',
    range: {
       'min':  0,
       'max':  30
    }
});

var basicSliderValue = document.getElementById('basic_slider_value');

basic_slider.noUiSlider.on('update', function( values, handle ) {
    basicSliderValue.value = values[handle];
});

basicSliderValue.addEventListener('change', function(){
    basic_slider.noUiSlider.set(this.value);
});

controller

@GetMapping
    public String newCampaign(@RequestParam(value = "appId", required = false) Integer appId, Model model) {

        CampaignResource campaign = new CampaignResource();
        if (appId != null) {
            App app = appService.getApp(appId);
            AppResource res = appConverter.convert(app);
            campaign.setApp(res);
        }
        return showPage(campaign, model);
    }

    protected String showPage(CampaignResource campaign, Model model) {

        model.addAttribute("campaignForm", campaign);
        model.addAttribute("appList", campaignService.getApps());
        model.addAttribute("publisherList", campaignService.getPublishers());
        model.addAttribute("sourceList", campaignService.getSources());
        return "campaigns/campaign-edit";
    }


    @PostMapping
    public String createCampaign(@ModelAttribute("campaignForm") @Validated CampaignResource resource, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return showPage(resource, model);
        }

        return saveCampaign(0, resource);
    }

    @GetMapping("/{campaignId}")
    public String editCampaign(@PathVariable int campaignId, Model model) {

        Campaign campaign = campaignService.getCampaign(campaignId);
        CampaignResource res = campaignConverter.convert(campaign);

        return showPage(res, model);
    }


    @PostMapping("/{campaignId}")
    public String updateCampaign(@PathVariable int campaignId, @ModelAttribute("campaignForm") @Validated CampaignResource resource, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return showPage(resource, model);
        }
        return saveCampaign(campaignId, resource);
    }

    protected String saveCampaign(int campaignId, CampaignResource resource) {
        Campaign campaign = populateCampaign(campaignId, resource);
        int appId = getAppId(resource);
        int publisherId = getPublisherId(resource);
        int sourceId = getSourceId(resource);

        if (campaignId == 0) {
            campaignService.createCampaign(campaign, appId, publisherId, sourceId);
        } else {
            campaignService.updateCampaign(campaign, appId, publisherId, sourceId);
        }

        return "redirect:/campaigns";
    }

    protected Campaign populateCampaign(int campaignId, CampaignResource resource) {
        Campaign campaign = null;
        if (campaignId == 0) {
            campaign = new Campaign();
            campaign.setTimeAdded(new Date());
        } else {
            campaign = campaignService.getCampaign(campaignId);
        }

        campaign.setCampaignName(resource.getCampaignName());
        campaign.setDescription(resource.getDescription());
        campaign.setStatus(resource.isStatus() ? UserEnums.StatusCampaign.ACTIVE : UserEnums.StatusCampaign.INACTIVE);
        campaign.setSessionLifespan(resource.getSessionLifespan());

        return campaign;
    }

service

@Transactional
    public Campaign createCampaign(Campaign campaign, int appId, int publisherId, int sourceId) {

        App app = appRepository.findOne(appId);
        campaign.setApp(app);

        Publisher publisher = publisherRepository.findOne(publisherId);
        campaign.setPublisher(publisher);

        Source source = sourceRepository.findOne(sourceId);
        campaign.setSource(source);

        campaign = campaignRepository.save(campaign);
        return campaign;
    }

    @Transactional
    public Campaign updateCampaign(Campaign campaign, int appId, int publisherId, int sourceId) {

        campaign.setApp(appRepository.findOne(appId));
        campaign.setPublisher(publisherRepository.findOne(publisherId));
        campaign.setSource(sourceRepository.findOne(sourceId));
        campaign = campaignRepository.save(campaign);

        return campaign;
    }

converter

@Override
    public CampaignResource convert(Campaign campaign) {

        CampaignResource resource = new CampaignResource();

        resource.setId(campaign.getId());
        resource.setCampaignName(campaign.getCampaignName());
        resource.setDescription(campaign.getDescription());
        resource.setStatus(campaign.getStatus() == StatusCampaign.ACTIVE);
        resource.setSessionLifespan(campaign.getSessionLifespan());

        if(campaign.getApp() != null) {
            resource.setApp(appConverter.convert(campaign.getApp()));
        }

        if(campaign.getPublisher() != null) {
            resource.setPublisher(publisherConverter.convert(campaign.getPublisher()));
        }

        if(campaign.getSource() != null) {
            resource.setSource(sourceConverter.convert(campaign.getSource()));
        }

        return resource;
    }

error

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'campaignForm' on field 'sessionLifespan': rejected value [7.00]; codes [typeMismatch.campaignForm.sessionLifespan,typeMismatch.sessionLifespan,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [campaignForm.sessionLifespan,sessionLifespan]; arguments []; default message [sessionLifespan]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'sessionLifespan'; nested exception is java.lang.NumberFormatException: For input string: "7.00"]

When i move slider it change value in input field, but when i click on save button nothing happend. If i remove th:field="*{sessionLifespan}"from input tag then it save data from form and for sessionLifespan in database it save value 0.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To address the last problem, change your javascript code like this:

var basic_slider = document.getElementById('basic_slider');
var basicSliderValue = document.getElementById('basic_slider_value');

noUiSlider.create(basic_slider, {
    start: basicSliderValue.value,
    step: 1,
    behaviour: 'tap',
    connect: 'upper',
    range: {
       'min':  0,
       'max':  30
    }
});

basic_slider.noUiSlider.on('update', function( values, handle ) {
    basicSliderValue.value = values[handle];
});

basicSliderValue.addEventListener('change', function(){
    basic_slider.noUiSlider.set(this.value);
});

The above code will get the value from the field before creating the slider and set the initial value to it. Ofc you still need to use parseInt if you want it to be a int value.

As you may noticed the cause of that problem was pretty simple but still hard to find because you did not notice that there was an error during the validation of the model attribute. In order to prevent similar problems i suggest you to either log any BindingResult related errors or use the th:errors attribute to display them in the form. Both ways will not fix the problem itself, but they will provide the information to fix it. Make sure to check this to learn more about th:error and Form validation in general.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...