简体   繁体   中英

Yii - How can I submit a form and send a user to a given anchor?

I need to achieve in Yii something like this:

<form action="somescript.php#fragment-id">

Once the form get's submitted, the success message should appear in front of the user eyes. At this time, the message is displaying BUT, the browser goes back to the top.

<?php $form=$this->beginWidget('CActiveForm', array(
                    'id'=>'contact-form',
                    'enableClientValidation'=>true,
                )); ?>

  //form here
  <?php echo CHtml::submitButton('send')); ?>

<?php $this->endWidget(); ?>

I see something here called actionPrefix , but it seems to be coming from another class:

CWidget

http://www.yiiframework.com/doc/api/1.1/CActiveForm

I've tried to add actionPrefix like so:

<?php $form=$this->beginWidget('CActiveForm', array(
                    'id'=>'contact-form',
                    'enableClientValidation'=>true,
                    'actionPrefix'=>'fragment-id'
                )); ?>

No dice.

Please advice

Use the action attribute of CActiveForm . repalce 'controller/acion' with your specific needs.

  <?php $form=$this->beginWidget('CActiveForm', array(
                        'id'=>'contact-form',
                        'enableClientValidation'=>true,
                        'action'=>array('controller/acion','#'=>'fragment-id')
                    )); ?>

In the controller/action that receives your form submit, once the form is processed, simply redirect to the URL you want. eg:

$this->redirect(Yii::app()->request->baseUrl."/myurl#fragment-id");

You can even get real fancy and use this short jQuery scroll to function:

function goToByScroll(id){
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}

Which get's called like so:

goToByScroll("theIdIWantToGoTo");

You are looking at the wrong option. what you need its action :

<?php $form=$this->beginWidget('CActiveForm', array(
                    'id'=>'contact-form',
                    'action'=>$this->createUrl('')."#fragment-id",
                    'enableClientValidation'=>true,
                )); ?>

  //form here
  <?php echo CHtml::submitButton('send')); ?>

<?php $this->endWidget(); ?>

The empty params for the createUrl its to generate an URL for the ccurrently requested URL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM