Cosmin
Cosmin

Reputation: 93

Redirect to link with anchor

I have a view file 'profile.php' with a tab menu

<ul class="nav nav-tabs">
    <li class="active">
        <a href="#profile" data-toggle="tab">Information</a>
    </li>
    <li>
        <a href="#password" data-toggle="tab">Change password</a>
    </li>
    <li>
        <a href="#account" data-toggle="tab">Delete account</a>
    </li>
</ul>

<div class="tab-content">
        <div class="tab-pane fade in active" id="profile">
            ... profile content
        </div>

        <div class="tab-pane fade" id="password">
            ... password content
        </div>

        <div class="tab-pane fade" id="account">
            <?php $form = ActiveForm::begin([
                                     'method' => 'post',
                                     'action' => ['user/delete'],
                                      ]);
            ?>

            <div class="col-lg-12">
                <?php echo $form->field($model, 'delpassword')
                                ->passwordInput(['maxlength' => true,'placeholder' => 'Password'])
                                ->label(false) 
                ?>
            </div>

            <div class="form-group">
                <?php echo Html::submitButton('Delete', ['class' => 'custom-button']) ?>
            </div>

            <?php ActiveForm::end(); ?>
        </div>
</div>

I can go to the account tab by adding #tab_account to the end of url

In UserController i have this action :

public function actionDelete()
{   
    $id = Yii::$app->user->identity->user_id;

    $model = $this->findModel($id); 

    $model->setscenario('delete_account');

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {

        $model->delete();
        return $this->goHome();

    } else {

        return $this->render('profile', [
                'model' => $model,
        ]);
    }
}

If the account was not deleted for some reason the action renders the profile.php but on the first tab (#tab_profile). I want to redirect directly to the account tab. I tried return $this->refresh(#tab_account); but i end up in a redirect loop.

Upvotes: 2

Views: 7356

Answers (1)

Tony
Tony

Reputation: 5867

You can redirect to another action. E.g. I assume that you have actionProfile to render user's profile page and actionDelete to delete it. So in actionDelete when profile cannot be deleted you redirect user to profile page with #tab_account.

public function actionDelete()
{   
    //your code for deleting
    } else {

        return $this->redirect(['profile', 'id' => $id, '#' => 'tab_account']);
    }
}

Upvotes: 6

Related Questions