Form is not getting submitted when render partial in Yii - ajax

I am partially rendering a form in a view in which user can add subaccounts(profiles). The view in which the form is called is another form where all subaccounts are listed as radiolist.
Below is my view.
<div class="inputs">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'selectUser-form',
'enableAjaxValidation' => false,
)); ?>
<?php echo CHtml::activeRadioButtonList($model,'id', $model->getSubAccounts(),array('prompt'=>'Please Select'));?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Book Now' : 'Save'); ?>
<?php echo CHtml::Button('Cancel',array('submit'=>array('cancel','id'=>$model->a_id)));?>
<?php $this->endWidget(); ?>
<div id="data"></div>
<?php echo CHtml::ajaxButton ("Add Users",
CController::createUrl('/user/user/addSubAccount'),
array('update' => '#data'));
?>
Below is my addSubAccount action.
public function actionAddSubAccount()
{
$profile=new YumProfile;
if (isset($_POST['YumProfile']))
{
$profile->attributes = $_POST['YumProfile'];
$profile->user_id=Yii::app()->user->id;
if($profile->save())
$this->redirect(array('/home/create'));}
if(!Yii::app()->request->isAjaxRequest){
$this->render('subaccount_form', array('profile'=>$profile));}
else{
$this->renderPartial('subaccount_form', array('profile'=>$profile));
}
}
Below is subaccount_form.
<?php $this->title = Yum::t('SubAccounts');?>
<div class="wide form">
<?php $activeform = $this->beginWidget('CActiveForm', array(
'id'=>'subaccount-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
));
?>
<div class="row"> <?php
echo $activeform->labelEx($profile,'Firstname');
echo $activeform->textField($profile,'firstname');
echo $activeform->error($profile,'firstname');
?> </div>
<div class="row"> <?php
echo $activeform->labelEx($profile,'Lastname');
echo $activeform->textField($profile,'lastname');
echo $activeform->error($profile,'lastname');
?> </div>
<div class="row"> <?php
echo $activeform->labelEx($profile,'Age');
echo $activeform->textField($profile,'age');
echo $activeform->error($profile,'age');
?> </div>
<div class="row submit">
<?php echo CHtml::submitButton(Yum::t('Add')); ?>
</div>
<?php $this->endWidget(); ?>
My form is rendering. But it's not getting submitted.What am i doing wrong?
After submitting,I need the view to be refreshed and to display the newly added user as an option in the radio list.
EDIT:
I tried like adding the following in the CActiveForm Widget array:
'action' => array( '/user/user/addsubAccount' ),
But still no result.Instead it is saving my data two times when i go through my direct way,meaning render method. :-(

It is because
'enableAjaxValidation'=>true,
Ajax validation is set to true in your form. Set its value to false
'enableAjaxValidation'=>FALSE, and then your form will submit :)
and if you want it to be true only then you should uncomment
$this->performAjaxValidation($model);
in your controller's action
Update 1
if(!Yii::app()->request->isAjaxRequest){
$this->render('subaccount_form', array('profile'=>$profile));}
else{
//change this line
$this->renderPartial('subaccount_form', array('profile'=>$profile),FALSE,TRUE);
}
This link might help you

on renderPartial the action attribute of the form is set to the current page instead of being set to the actual update or create url
My Solution
$form=$this->beginWidget('CActiveForm', array(
'id'=>'country-form',
'action' => Yii::app()->createUrl(is_null(Yii::app()->request->getParam('id'))?'/country/create':'/country/update/'.Yii::app()->request->getParam('id')),

Related

How to create an Ajax Filter to display custom post types in WordPress

I asked a question to this topic before but since it seems like this requires just custom coding, I need help from the experts. I am not a coder, I design and build website in Webflow but want to learnt to convert them to a WordPress theme.
I have a Custom Post Type and want to display all of these posts on a page, however, above the displayed posts I want a filter, so that the user can click on a category and only see custom posts for that category (without page reload).
I registered a custom taxonomy and added categories for this. I see this on so many website, this seems to be a super common thing, and that's why I am so surprised that there is no plugin to achieve that. But anyway, here is an example of what I want to achieve: https://www.hauserlacour.de/en/work
I know that it has something to do with custom queries and AJAX. But I couldn't find a beginner friendly tutorial to achieve what I need.
Can anyone help me with the code below and what is needed to turn my custom taxonomy into a filter?
And here is the code I have as of now:
<?php get_header( 'page-posttest' ); ?>
<div class="projekte-wrapper-1">
<?php $terms = get_terms( array(
'taxonomy' => 'art',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false
) ) ?>
<?php if( !empty( $terms ) ) : ?>
<div class="taxonomy-wrapper">
<?php foreach( $terms as $term ) : ?>
<?php echo $term->name; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php
$projekte_query_args = array(
'post_type' => 'projekte',
'nopaging' => true,
'order' => 'ASC',
'orderby' => 'date'
)
?>
<?php $projekte_query = new WP_Query( $projekte_query_args ); ?>
<?php if ( $projekte_query->have_posts() ) : ?>
<div class="posts-wrapper">
<?php while ( $projekte_query->have_posts() ) : $projekte_query->the_post(); ?>
<?php PG_Helper::rememberShownPost(); ?>
<?php $image_attributes = !empty( get_the_ID() ) ? wp_get_attachment_image_src( PG_Image::isPostImage() ? get_the_ID() : get_post_thumbnail_id( get_the_ID() ), 'full' ) : null; ?>
<h1 class="heading-14"><?php the_title(); ?></h1>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</div>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.', 'test' ); ?></p>
<?php endif; ?>
</div>
<?php get_footer( 'page-posttest' ); ?>

Show 'Advanced Custom Field' Image

I'm having problems getting the image field from Advanced Custom Field plugin. I'm using it to set an image for custom taxonomy category named "aktuelni_ponudi_category". I have displayed the name of the category and its link, but can't fix the problem with the image. I also want to create a shortcode, so here is my code:
function my_vc_shortcode( $atts ) {
$categories = get_categories( array(
'taxonomy' => 'aktuelni_ponudi_category',
'hide_empty' => '0',
'order' => 'DESC'
)); ?>
<div class="row">
<?php
foreach($categories as $category) { ?>
<div class="col-md-4">
<a href="<?php echo get_category_link($category->cat_ID); ?>">
<?php echo $category->name; ?>
</a>
<?php echo '<img src="' . the_field('acf_image') . '">'; ?>
</div>
<?php }
?>
</div>
<?php }
add_shortcode( 'my_vc_php_output', 'my_vc_shortcode');
I'm hoping for an answer...
If you use custom fields on a taxonomy term there is a special syntax to get that data: you should call the field function with a parameter composed of the taxonomy name and the term id, like here:
the_field('acf_field','aktuelni_ponudi_category_' . $category->cat_ID);
You can read more about it here: https://www.advancedcustomfields.com/resources/get-values-from-a-taxonomy-term/

Yii2 Unable append Ajax success to CKeditor

I was trying to create a newsletter module using Yii2 basic.
This is my scenario,
If a predefined template is available, I have to select that template.
If template is selected the subject and content should be loaded automatically.
For this I am using an Ajax.My Ajax is working perfectly and I appended the newsletter subject with Ajax success,Problem occurred when I tried to append the newsletter content.Hence I am using CKeditor.
My Form
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\modules\admin\models\NewsletterTemplates;
/* #var $this yii\web\View */
/* #var $model app\modules\admin\models\Letter */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="letter-form form_style " >
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'letter_template_id')->dropDownList(
ArrayHelper::map(NewsletterTemplates::find()->all(),'newsletter_temp_id','newsletter_temp_subject'),
['prompt' => 'Select','class'=>'form-contol','onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('admin/letter/temp?id=').'"+$(this).val(), function( data ) {
var message = data.split("::");
//alert(message[1]);
$( "#letter-letter_sub" ).val( message[0] );
$( "#letter-letter_content" ).val( message[1] );
});'
]);
?>
<?php //echo $form->field($model, 'letter_template_id')->textInput(['class'=>'form-contol']) ?>
<?= $form->field($model, 'letter_to')->textInput(['class'=>'form-contol']) ?>
<?= $form->field($model, 'letter_sub')->textInput(['class'=>'form-contol']) ?>
<?= $form->field($model, 'letter_content')->textarea(['class'=>'ckeditor']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Send' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Can anyone help with this......
Thanks in advance....
Hi Guys I found out the answer
I just replace the instances of the CKeditor.
<?= $form->field($model, 'letter_template_id')->dropDownList(
ArrayHelper::map(NewsletterTemplates::find()->all(),'newsletter_temp_id','newsletter_temp_subject'),
['prompt' => 'Select','class'=>'form-contol','onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('admin/letter/temp?id=').'"+$(this).val(), function( data ) {
var message = data.split("::");
$( "#letter-letter_sub" ).val( message[0] );
CKEDITOR.instances["letter-letter_content"].destroy(true);
CKEDITOR.replace( "letter-letter_content" );
var editor = CKEDITOR.instances[ "letter-letter_content" ];
editor.setData(message[1]);
});'
]);
?>
Thank you for your supports

ajax not clearing form on submit

I have a form and want to submit through ajax. It posts but it doesn't clear form onclick success. I've also tried .done(function). I've also tried alert data on success and error (thinking must be error) but it doesn't alert anything either.
<?php echo CHtml::ajaxSubmitButton(
'Comment',
'review/ajaxComment',
array(
'type'=>'POST',
'dataType'=>'json',
'success'=>'js:function(data){
if(data.result==="success"){
document.getElementById("review-form").reset();
alert("this worked");
}else{
console.log(error)
}
}'
)
)?>
form
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'review-form',
'enableAjaxValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true),)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="rating-row">
<?php $this->Widget('CStarRating', array(
'model'=>$model,
'attribute'=> 'star',
'minRating'=>.5 ,
'maxRating'=>5 ,
'starCount'=>5 ,
'ratingStepSize'=>.5
));?>
</div>
<div class="rating-row">
<label>Reviews</label>
<?php echo $form->textArea($model,'review'); ?>
<?php echo $form->error($model,'review'); ?>
</div>
Method 1:
Assign a class for all textbox, textarea, Dropdown. For example, frm_inp_ctrl
Then, do $(".frm_inp_ctrl").val(""); in ajax done()
Method 2:
Do reset with form id as below.
$("#review-form :input").val("");

can't use multiple ajaxLink for loading CJuiDialog widget

I have a problem when using multiple ajaxLink for loading CJuiDialog widget in yii. I'm using multiple dropdowns, each dropdown's value determine next dropdown.
Here is my code for viewing first dropdown and a link to create new item using Cdialog widget.
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>false,
)); ?>
<div class="row">
<?php
echo $form->labelEx($model,'uname'); ?>
<?php echo $form->dropDownList($model,'uname',$model- >getUniversityList(),array('onchange'=>'getSchemes(this.value)','empty'=>'Select university')); ?>
<?php echo $form->error($model,'uname'); ?>
<?php //create university dialoge box
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new university',array('university/dialoge'),array(
'success'=>'js:function(data){
$("#createUniversity").dialog("open");
document.getElementById("create_university").innerHTML=data;
}'));
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createUniversity',
'options'=>array(
'title'=>'Create University',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_university'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="scheme">
</div>
</div>
<?php $this->endWidget(); ?>
</div>
<input type="hidden" id="url" value="<?php echo $this->createUrl('scheme/test'); ?>">
this works pretty good.
here is the javascript code for loading next dropdown in the same view file
<script type="text/javascript">
function getSchemes(uid)
{
if(uid==""){
document.getElementById("scheme").innerHTML='';
return;
}
jQuery(function($){
var url=document.getElementById("url").value;
$.post(url, { uid:uid },
function(data){
document.getElementById("scheme").innerHTML=data;
document.getElementById("scheme_link").style.display="block";
});
});
}
The scheme drop down is loaded as the scheme view code is
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<?php
echo "<div class=".'label'."><label for=".'sch'.">Scheme</label></div>";
echo "<select id=".'sch'." onchange='getDepartments(this.value);'>";
echo "<option value=".''.">"."Select Scheme</option>";
foreach($schemes as $s)
{
echo "<option value='".$s->schemeid."' >".$s->scheme_name."</option>";
}
echo "</select>";
?>
<?php
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new Scheme',array('scheme/dialoge','id'=>5),array(
'success'=>'js:function(data1){
$("#createScheme").dialog("open");
document.getElementById("create_scheme").innerHTML=data;
}'));?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createScheme',
'options'=>array(
'title'=>'Create Scheme',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_scheme'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="department">
</div>
<input type="hidden" id="urldepart" value="<?php echo $this->createUrl('department/test'); ?> ">
the second ajaxLink is shown as create new scheme but on clicking the link it shows the old create university dialog box instead of create scheme.
The simplest solution for this is to create the ID of the element that is causing problems as random.
Try adding:
'id' => 'some-element'.uniqid() // avoid mutliple ajax request because of using live
in the $htmlOptions array of ajaxLink

Resources