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
Related
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' ); ?>
<main class="main aktualitasu_saraksta_konteineris" role="main">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'group_by' => 'date',
'order' => 'DESC',
'ignore_sticky_posts' => 1
);
$query = new WP_Query($args);
?>
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
<?php get_template_part( 'parts/loop', 'news' ); ?>
<?php endwhile; endif; wp_reset_postdata();?>
</main>
How to add load more button that load posts with ajax?
You will need to do this in javascript rather than in php look at this https://www.w3schools.com/jquery/jquery_ajax_get_post.asp. You will need to add button in html say
<button id="load_more" type="button">Load More</button>
And then in javascript (this is an example using jQuery)
$("#load_more").click(function(){
$.get("your/route", function(data, status){
//here you can add the data to the page depending on what the data is
});
});
your/route is whatever route you have set in php for fetching more posts
How can i use ActiveForm with these requirements?
Submit form with ajax.
Before submitting with ajax: Check if error exits.
After submitting: Display error of field under field's input if the server responses unsuccess saving result.
This is your form in view. I prefer use different actions for validation and saving. You can join them into single method.
<?php $form = \yii\widgets\ActiveForm::begin([
'id' => 'my-form-id',
'action' => 'save-url',
'enableAjaxValidation' => true,
'validationUrl' => 'validation-rul',
]); ?>
<?= $form->field($model, 'email')->textInput(); ?>
<?= Html::submitButton('Submit'); ?>
<?php $form->end(); ?>
In validation action you should write. It validates your form and returns list of errrs to client. :
public function actionValidate()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
And this is save action. In validate input data for security:
public function actionSave()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ['success' => $model->save()];
}
return $this->renderAjax('registration', [
'model' => $model,
]);
}
This code will validate your form in actionValidate() and. For submitting your form via AJAX use beforeSubmit event. In your javascript file write:
$(document).on("beforeSubmit", "#my-form-id", function () {
// send data to actionSave by ajax request.
return false; // Cancel form submitting.
});
That's all.
Submit form with ajax.
Before submitting with ajax: Check if error exits. yii display error if any by default....... :)
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model backend\models\search\JobSearch */
/* #var $form yii\bootstrap\ActiveForm */
?>
<div class="job-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
//'method' => 'get',
'options' => ['id' => 'dynamic-form111']
]); ?>
<?php echo $form->field($searchModel, 'id') ?>
<?php echo $form->field($searchModel, 'user_id') ?>
<?php echo $form->field($searchModel, 'com_id') ?>
<?php echo $form->field($searchModel, 'job_no') ?>
<?php echo $form->field($searchModel, 'court_id') ?>
<?php // echo $form->field($model, 'case_no') ?>
<?php // echo $form->field($model, 'plainttiff') ?>
<?php // echo $form->field($model, 'defendant') ?>
<?php // echo $form->field($model, 'date_fill') ?>
<?php // echo $form->field($model, 'court_date') ?>
<?php // echo $form->field($model, 'status_id') ?>
<?php // echo $form->field($model, 'created_at') ?>
<?php // echo $form->field($model, 'updated_at') ?>
<div class="form-group">
<?php echo Html::submitButton('Search', ['class' => 'btn btn-primary','id'=>'submit_id']) ?>
<?php echo Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('body').on('beforeSubmit', 'form#dynamic-form111', function () {
var form = $(this);
// return false if form still have some validation errors
if (form.find('.has-error').length)
{
return false;
}
// submit form
$.ajax({
url : form.attr('action'),
type : 'get',
data : form.serialize(),
success: function (response)
{
var getupdatedata = $(response).find('#filter_id_test');
// $.pjax.reload('#note_update_id'); for pjax update
$('#yiiikap').html(getupdatedata);
//console.log(getupdatedata);
},
error : function ()
{
console.log('internal server error');
}
});
return false;
});
});
</script>
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')),
i'm loading a post with ajax.
The code is
$(document).ready(function(){
loadPostsFun = function(){
$.ajax({
url: "http://lab1.koalamedia.es/ajax/",
//url: "/random/",
success: function(response){
$("#randomPost").html( response );
}
});
};
$("#another").click(function(){
loadPostsFun();
return false;
});
});
The response is generated by a custom template with this code:
<?php
query_posts('showposts=1&orderby=rand');
the_post();
$args = array( 'numberposts' => 1, 'orderby' => 'date' );
$rand_posts = get_posts( $args );
?>
<?php
foreach( $rand_posts as $post ) : setup_postdata($post);
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( is_front_page() ) { ?>
<h2 class="entry-title"><?php the_title(); ?></h2>
<?php } else { ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php } ?>
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
<?php comments_popup_link(__('Comments (0)'), __('Comments (1)'), __('Comments (%)')); ?>
</div><!-- .entry-content -->
</div><!-- #post-## -->
<?php
//comments_template( '', true ); //this doesn't work
comment_form();
//wp_list_comments(''); //this doesn't work
?>
<?php endforeach; ?>
The ajax request works but the comments doesn't show.All the post data is there.
How can i show the comments?
neither comments_template or wp_list_comments work.
You can view a demo or download the template sample i've done here
Without much tweaking wp_list_comments() works in a comments template (usually comments.php) only.
Use get_comments(), pass the post ID as parameter:
$comments = get_comments(array ( 'post_id' => $post->ID );
if ( $comments )
{
foreach ( $comments as $comment )
{
print "<li>$comment->comment_author<br>$comment->comment_content</li>";
}
}
i've found the problem, i forgot to set the global variable:
global $withcomments;
i was using
$withcomments = true;
comments_template();
but without the global it didn't work.
Now works like normal comments do.