How to get data from multiple dropdown without using submit button - yii2

Hi here's my controller
public function actionCreate()
{
$this->layout = "main";
$location = \Yii::$app->getRequest()->getCookies()->getValue( 'location_id' );
if ( $location != NULL )
{
$model = new ScreenTicketBooking();
if ( $model->load( Yii::$app->request->post() ) )
{
return $this->redirect( [ 'time', 'ids' => $model->show_date, 'id' => $model->movie_id ] );
}
else
{
return $this->render( 'create', [
'model' => $model,
] );
}
}
else
{
return $this->redirect( [ 'site/home' ] );
}
}
here's my view
<?php
use app\models\Locations;
use app\models\Movies;
use app\models\MovieShows;
use app\models\ScreenClasses;
use app\models\ScreenClassSeats;
use app\models\Screens;
use app\models\ScreenShowTimes;
use app\models\Theatres;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\ScreenTicketBooking */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="screen-ticket-booking-form col-md-4">
<?php $form = ActiveForm::begin(); ?>
<?php
$location = \Yii::$app->getRequest()->getCookies()->getValue( 'location_id' );
$movies = MovieShows::find()->where( [ 'location_id' => $location ] )->andWhere( [ '>', 'end_date',
date( 'Y-m-d' ) ] )->all();
if ( $movies != NULL )
{
foreach ( $movies as $movie )
{
$dataCategory[ ] = ArrayHelper::map( Movies::find()->where( 'status=:stat', [ 'stat' => 0 ] )
->andWhere( [ 'id' => $movie->movie_id ] )->all(), 'id',
'movie_name' );
}
}
else
{
$dataCategory = NULL;
}
$newArray = [ ];
if ( $movies != NULL )
{
foreach ( $dataCategory as $array )
{
foreach ( $array as $k => $v )
{
$newArray[ $k ] = $v;
}
}
}
echo $form->field( $model, 'movie_id' )->dropDownList( $newArray,
[ 'prompt' => '-Choose a Movie-',
'onchange' => '
$.get( "' . Url::toRoute( 'screenticketbooking/dependdrop' ) . '", { id: $(this).val() } )
.done(function( data )
{
$( "select#title" ).html( data );
});
' ] )->label( '' ); ?>
<?php $dataPost = ArrayHelper::map( MovieShows::find()
->where( 'movie_id=:mov_id', [ 'mov_id' => $model->movie_id ] )
->asArray()->all(), 'id', 'start_date' );
echo $T = $form->field( $model, 'show_date' )
->dropDownList(
$dataPost,
[ 'id' => 'title', 'prompt' => '-Select a Date-' ]
)->label( '' );
?>
<div class="form-group">
<?=
Html::submitButton( $model->isNewRecord ? Yii::t( 'app', 'OK' ) : Yii::t( 'app', 'Update' ),
[ 'name' => 'submit', 'class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary',
'id' => 'ajith' ] ) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
both are working flawlessly but now what i want is not to use a submit button and when both dropdowns are selected then automatically get redirected to action Time. i am using a two way dependent dropdown. how can i achieve this ?

Try this.
<?php $dataPost = ArrayHelper::map( MovieShows::find()
->where( 'movie_id=:mov_id', [ 'mov_id' => $model->movie_id ] )
->asArray()->all(), 'id', 'start_date' );
echo $T = $form->field( $model, 'show_date' )
->dropDownList(
$dataPost,
[ 'id' => 'title', 'prompt' => '-Select a Date-', 'onchange' => 'this.form.submit()' ]
)->label( '' );
?>
using this when you select 'show_date' after that submit your form.

Related

Can't delete selected image when update the form by using Yii kartik fileinput

I refer to this link https://github.com/jaradsee/faktharm/blob/master/controllers/PhotoLibraryController.php
to upload multiple images but when I try to delete the selected image in update form it showing me these error
(image1)
(image2)
For image 2, why the url link always give products%252Fdeletefile-ajax (give number 25)
Below is my code, please help me to check what's goes wrong, thank you!
Uploads.php
class Uploads extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'uploads';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['file_name'], 'required'],
[['upload_id'], 'integer'],
[['create_date'], 'safe'],
[['ref'], 'string', 'max' => 100],
[['file_name', 'real_filename'], 'string', 'max' => 150],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'upload_id' => 'Upload ID',
'ref' => 'Ref',
'file_name' => 'File Name',
'real_filename' => 'Real Filename',
'create_date' => 'Create Date',
];
}
}
Products.php
class Products extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
//public $file;
const UPLOAD_FOLDER='products';
public static function tableName()
{
return 'products';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['productName', 'productDescription', 'productPrice', 'categoryId', 'brandId', 'productStatus'], 'required'],
[['productDescription', 'productStatus'], 'string'],
[['productPrice'], 'number'],
[['categoryId', 'brandId'], 'integer'],
[['productName','ref'], 'string', 'max' => 100],
[['brandId'], 'exist', 'skipOnError' => true, 'targetClass' => Brands::className(), 'targetAttribute' => ['brandId' => 'brandId']],
[['categoryId'], 'exist', 'skipOnError' => true, 'targetClass' => Categorys::className(), 'targetAttribute' => ['categoryId' => 'categoryId']],
[['ref'],'unique']
// ['productImage', 'file','maxFiles'=>5],
//[['file'],'productImage']
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'productId' => 'Product ID',
'productName' => 'Product Name',
'productDescription' => 'Product Description',
'productPrice' => 'Product Price',
'ref' => 'Product Image',
'categoryId' => 'Category',
'brandId' => 'Brand',
'productStatus' => 'Product Status',
];
}
/**
* Gets query for [[Brand]].
*
* #return \yii\db\ActiveQuery
*/
public function getBrand()
{
return $this->hasOne(Brands::className(), ['brandId' => 'brandId']);
}
/**
* Gets query for [[Category]].
*
* #return \yii\db\ActiveQuery
*/
public function getCategory()
{
return $this->hasOne(Categorys::className(), ['categoryId' => 'categoryId']);
}
public function getImages()
{
return $this->hasMany(Images::className(), ['productId' => 'productId']);
}
public static function getUploadPath(){
return Yii::getAlias('#webroot').'/'.self::UPLOAD_FOLDER.'/';
}
public static function getUploadUrl(){
return Url::base(true).'/'.self::UPLOAD_FOLDER.'/';
}
public function getThumbnails($ref,$event_name){
$uploadFiles = Uploads::find()->where(['ref'=>$ref])->all();
$preview = [];
foreach ($uploadFiles as $file) {
$preview[] = [
'url'=>self::getUploadUrl(true).$ref.'/'.$file->real_filename,
'src'=>self::getUploadUrl(true).$ref.'/thumbnail/'.$file->real_filename,
'options' => ['title' => $event_name]
];
}
return $preview;
}
}
ProductsController.php
namespace backend\controllers;
use Yii;
use backend\models\Products;
use backend\models\Uploads;
use backend\models\ProductsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Json;
use yii\widgets\ActiveForm;
use yii\web\UploadedFile;
use yii\helpers\Url;
use yii\helpers\html;
use yii\helpers\BaseFileHelper;
use yii\helpers\ArrayHelper;
/**
* ProductsController implements the CRUD actions for Products model.
*/
class ProductsController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
// 'access' => [
// 'class' => AccessControl::className(),
// 'rules' => [
// [
// 'actions' => ['view','update','_form','index','_search','create','uploadAjax','createDir'],
// 'allow' => true,
// 'roles' => ['admin'],
// ],
// ],
// ],
];
}
/**
* Lists all Products models.
* #return mixed
*/
public function actionIndex($pageSize = 10)
{
$searchModel = new ProductsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $pageSize);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'pageSize' => $pageSize,
]);
}
/**
* Displays a single Products model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Products model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
/*public function actionCreate()
{
$model = new Products();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->imageFiles = UploadedFile::getInstances($model, 'productImage');
return $this->redirect(['view', 'id' => $model->productId]);
}
return $this->render('create', [
'model' => $model,
]);
}*/
public function actionCreate()
{
$model = new Products();
if ($model->load(Yii::$app->request->post())) {
$this->Uploads(false);
if($model->save()){
return $this->redirect(['view', 'id' => $model->productId]);
}
}
else{
$model->ref = substr(Yii::$app->getSecurity()->generateRandomString(),10);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Products model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
list($initialPreview,$initialPreviewConfig) = $this->getInitialPreview($model->ref);
if ($model->load(Yii::$app->request->post())) {
$this->Uploads(false);
if($model->save()){
return $this->redirect(['view', 'id' => $model->productId]);
}
}
return $this->render('update', [
'model' => $model,
'initialPreview'=>$initialPreview,
'initialPreviewConfig'=>$initialPreviewConfig
]);
}
/**
* Deletes an existing Products model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
//$model = new Products();
//$this->findModel($id)->delete();
$model->$this->findModel($id);
$this->removeUploadDir($model->ref);
Uploads::deleteAll(['ref'=>$model->ref]);
$model->delete();
return $this->redirect(['index']);
}
/**
* Finds the Products model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Products the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Products::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
/*|*********************************************************************************|
|================================ Upload Ajax ====================================|
|*********************************************************************************|*/
public function actionUploadAjax(){
$this->Uploads(true);
}
private function CreateDir($folderName){
if($folderName != NULL){
$basePath = Products::getUploadPath();
if(BaseFileHelper::createDirectory($basePath.$folderName,0777)){
BaseFileHelper::createDirectory($basePath.$folderName.'/thumbnail',0777);
}
}
return;
}
private function removeUploadDir($dir){
BaseFileHelper::removeDirectory(Products::getUploadPath().$dir);
}
private function Uploads($isAjax=false) {
if (Yii::$app->request->isPost) {
$images = UploadedFile::getInstancesByName('upload_ajax');
if ($images) {
if($isAjax===true){
$ref =Yii::$app->request->post('ref');
}else{
$Products = Yii::$app->request->post('Products');
$ref = $Products['ref'];
}
$this->CreateDir($ref);
foreach ($images as $file){
$fileName = $file->baseName . '.' . $file->extension;
$realFileName = md5($file->baseName.time()) . '.' . $file->extension;
$savePath = Products::UPLOAD_FOLDER.'/'.$ref.'/'. $realFileName;
if($file->saveAs($savePath)){
if($this->isImage(Url::base(true).'/'.$savePath)){
$this->createThumbnail($ref,$realFileName);
}
$model = new Uploads;
$model->ref = $ref;
$model->file_name = $fileName;
$model->real_filename = $realFileName;
$model->save();
if($isAjax===true){
echo json_encode(['success' => 'true']);
}
}else{
if($isAjax===true){
echo json_encode(['success'=>'false','eror'=>$file->error]);
}
}
}
}
}
}
private function getInitialPreview($ref) {
$datas = Uploads::find()->where(['ref'=>$ref])->all();
$initialPreview = [];
$initialPreviewConfig = [];
foreach ($datas as $key => $value) {
array_push($initialPreview, $this->getTemplatePreview($value));
array_push($initialPreviewConfig, [
'caption'=> $value->file_name,
'width' => '120px',
'url' => Url::to(['/products/deletefile-ajax']),
'key' => $value->upload_id
]);
}
return [$initialPreview,$initialPreviewConfig];
}
public function isImage($filePath){
return #is_array(getimagesize($filePath)) ? true : false;
}
private function getTemplatePreview(Uploads $model){
$filePath = Products::getUploadUrl().$model->ref.'/thumbnail/'.$model->real_filename;
$isImage = $this->isImage($filePath);
if($isImage){
$file = Html::img($filePath,['class'=>'file-preview-image', 'alt'=>$model->file_name, 'title'=>$model->file_name]);
}else{
$file = "<div class='file-preview-other'> " .
"<h2><i class='glyphicon glyphicon-file'></i></h2>" .
"</div>";
}
return $file;
}
private function createThumbnail($folderName,$fileName,$width=250){
$uploadPath = Products::getUploadPath().'/'.$folderName.'/';
$file = $uploadPath.$fileName;
$image = Yii::$app->image->load($file);
$image->resize($width);
$image->save($uploadPath.'thumbnail/'.$fileName);
return;
}
public function actionDeletefileAjax(){
$model = Uploads::findOne(Yii::$app->request->post('key'));
if($model!==NULL){
$filename = Products::getUploadPath().$model->ref.'/'.$model->real_filename;
$thumbnail = Products::getUploadPath().$model->ref.'/thumbnail/'.$model->real_filename;
if($model->delete()){
#unlink($filename);
#unlink($thumbnail);
echo json_encode(['success'=>true]);
}else{
echo json_encode(['success'=>false]);
}
}else{
echo json_encode(['success'=>false]);
}
}
}
_form.php
<?php
//use kartik\file\FileInput;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use backend\models\Brands;
use backend\models\Categorys;
use yii\helpers\Url;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $model backend\models\Products */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="photo-library-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?php $form->errorSummary($model) ?>
<?= $form->field($model, 'ref')->hiddenInput(['maxlength' => 100])->label(false); ?>
<?= $form->field($model, 'productName')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'productDescription')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'productPrice')->textInput() ?>
<?=
$form->field($model, 'brandId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Brands::find()->where(['brandStatus'=>'active'])->all(),'brandId','brandName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a brand ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?=
$form->field($model, 'categoryId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Categorys::find()->where(['categoryStatus'=>'active'])->all(),'categoryId','categoryName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a category ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'productStatus')->dropDownList([ 'active' => 'Active', 'inactive' => 'Inactive', ], ['prompt' => 'Status']) ?>
<div class="form-group field-upload_files">
<label class="control-label" for="upload_files[]"> Product Images </label>
<div>
<?=
FileInput::widget([
'name' => 'upload_ajax[]',
//'attribute'=>'productImage[]',
//'name'=>'productImage[]',
'options' => [
'multiple'=>true,
'accept' => 'image/*',
//'id'=>'imageId',
],
'pluginOptions' => [
'initialPreview'=> $initialPreview,
'initialPreviewConfig'=> $initialPreviewConfig,
'deleteUrl'=>Url::to(['/products/deletefile-ajax']),
'showPreview' => true,
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'uploadAsync' => true,
'uploadUrl'=>Url::to(['/products/upload-ajax']),
'maxFileCount' => 5,
'allowedFileExtensions' => ['jpg', 'png','jpeg'],
'previewFileType' => ['jpg', 'png','jpeg'],
'overwriteInitial'=>false,
'uploadExtraData' => [
'ref'=>$model->ref
],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
'validateInitailCount'=>true,
'layoutTemplates'=>[
'actionZoom'=>'<button type="button" class="kv-file-zoom">{zoomIcon}</button>',
'actionUpload'=>'',
//'actionDelete'=>'<a>jj</a>',
//'footer' => '<div class="file-thumbnail-footer"><div class="file-caption-name" style="width:{width}">{caption}{size}</div>
//{progress}{actions}',
//'footer' => '<div class="file-thumbnail-footer"> <div class="file-caption-caption" title="{caption}"</div>'
//'actionDelete'=>'<button type="button" class="kv-file-remove"> {dataKey}{deleteUrl} {removeIcon}</button>',
],
],
'pluginEvents' => [
'filebatchselected' => 'function(event, files) {
$(this).fileinput("/products/upload-ajax");
}',
],
]);
?>
<br>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord? 'Save': 'Update', ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Cancel'), ['index', 'id' => $model->productId], ['class'=>'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
I found the solution my bad
need to change all the Url::to() in controller and _form
to this format solution
The detail answer as below
_form.php
<?php
//use kartik\file\FileInput;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use backend\models\Brands;
use backend\models\Categorys;
use yii\helpers\Url;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $model backend\models\Products */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="photo-library-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?php $form->errorSummary($model) ?>
<?= $form->field($model, 'ref')->hiddenInput(['maxlength' => 100])->label(false); ?>
<?= $form->field($model, 'productName')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'productDescription')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'productPrice')->textInput() ?>
<?=
$form->field($model, 'brandId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Brands::find()->where(['brandStatus'=>'active'])->all(),'brandId','brandName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a brand ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?=
$form->field($model, 'categoryId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Categorys::find()->where(['categoryStatus'=>'active'])->all(),'categoryId','categoryName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a category ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'productStatus')->dropDownList([ 'active' => 'Active', 'inactive' => 'Inactive', ], ['prompt' => 'Status']) ?>
<label>Product Images</label>
<?=
FileInput::widget([
'name' => 'upload_ajax[]',
//'attribute'=>'productImage[]',
//'name'=>'productImage[]',
'options' => [
'multiple'=>true,
'accept' => 'image/*',
//'id'=>'imageId',
],
'pluginOptions' => [
'initialPreview'=> $initialPreview,
'initialPreviewConfig'=> $initialPreviewConfig,
'showPreview' => true,
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'uploadAsync' => false,
'uploadUrl'=>Url::to('index.php?r=products/upload-ajax'),
'deleteUrl'=>Url::to('index.php?r=products/deletefile-ajax'),
'maxFileCount' => 5,
'allowedFileExtensions' => ['jpg', 'png','jpeg'],
'previewFileType' => ['jpg', 'png','jpeg'],
'overwriteInitial'=>false,
'enableResumableUpload'=>true,
'uploadExtraData' => [
'ref'=>$model->ref
],
'validateInitialCount'=>true,
'initialPreviewShowDelete' => true,
'layoutTemplates'=>[
'actionZoom'=>'<button type="button" class="kv-file-zoom">{zoomIcon}</button>',
'actionUpload'=>'',
'actionDelete' => '<button type="button" class="kv-file-remove" title="{removeTitle}" {dataKey}{dataUrl}><i class="glyphicon glyphicon-trash"></i></button>'
],
],
'pluginEvents' => [
// 'filebatchselected' => 'function(files) {
// $(this).fileinput("index.php?r=products/upload-ajax");
// }',
'filepredelete'=>'function(jqXHR){
var abort = true;
if (confirm("Are you sure you want to delete this image?")) {
abort = false;
}
return abort;
}'
],
]);
?>
<br>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord? 'Save': 'Update', ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Cancel'), ['index', 'id' => $model->productId], ['class'=>'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
ProductsController
private function getInitialPreview($ref) {
$datas = Uploads::find()->where(['ref'=>$ref])->all();
$initialPreview = [];
$initialPreviewConfig = [];
foreach ($datas as $key => $value) {
array_push($initialPreview, $this->getTemplatePreview($value));
array_push($initialPreviewConfig, [
'caption'=> $value->file_name,
'width' => '120px',
'url' => Url::to('index.php?r=products/deletefile-ajax'),
'key' => $value->upload_id
]);
}
return [$initialPreview,$initialPreviewConfig];
}

put spans and divs around paginate_links

I wanna style my links and in order to do that I need some spans and divs around it but I dunno how it's done when using paginate_links() from WordPress.
Can you help me to do that?
<div class="pagination">
<?php echo
$pagination = paginate_links( array(
'base' => add_query_arg( 'cpage', '%#%' ),
'format' => '',
'prev_text' => __('← Previous'),
'next_text' => __('Next →'),
'total' => ceil($total / $items_per_page),
'current' => $page,
'type' => 'plain'
));
?>
</div>
so far it looks like that
Just change li to div / span whatever. The main difference is to change your "type" from "plain" to "array" and then you can do what you want with it.
<?php
global $wp_query;
$big = 999999999; // need an unlikely integer
$prev_next = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'type' => 'array',
'prev_text' => __('← Previous'),
'next_text' => __('Next →')
) );
if($prev_next){ ?>
<ul>
<?php
foreach($prev_next as $key=>$val){
if (strpos($val,"'page-numbers current'") !== false) {
echo '<li class="active item">'.$val.'</li>';
} elseif (strpos($val,'"next page-numbers"') !== false || strpos($val,'"prev page-numbers"') !== false ) {
echo'<li>'.$val.'</li>';
} else {
echo '<li class="item">'.$val.'</li>';
}
} ?>
</ul>
<?php } ?>

How to use ACF into JSON via ajax in Wordpress

I'm trying to use the Advanced Custom Field (ACF) plugin to return JSON via ajax in WordPress.
The below code correctly returns the JSON data of the posts but is not giving me the ACF data inside each post.
How can I get that ACF data into JSON?
PHP File
add_shortcode("owt-ajax-shortcode", "owt_wpl_run_shortcode");
function owt_wpl_run_shortcode() {
ob_start();
include_once plugin_dir_path(__FILE__) . 'views/owt-ajax-page-view.php';
$template = ob_get_contents();
ob_end_clean();
echo $template;
}
add_action("wp_enqueue_scripts", "owt_include_scripts");
function owt_include_scripts() {
wp_enqueue_script("jquery");
}
add_action("wp_ajax_owt_ajax_lib", "owt_lib_ajax_handler_fn");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_lib_ajax_handler_fn");
function owt_lib_ajax_handler_fn() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$all_posts = get_posts(array(
"post_type" => "post",
"post_status" => "publish",
'posts_per_page' => 20,
'order' => 'DESC',
'orderby' => 'date',
'cat' => 66
));
header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
echo json_encode( $all_posts );
die;
}
}
wp_die();
}
JavaScript
<button id="btn-get-all-posts">Click to get All Posts</button>
<script>
jQuery(function () {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery("#btn-get-all-posts").on("click", function () {
var postdata = "action=owt_ajax_lib&param=get_all_posts";
jQuery.post(ajaxurl, postdata, function (response) {
console.log(response);
});
});
});
</script>
instead of use get_posts try your own query with WP_Query
here is an example code, please let me know if it works correctly(I didn't test it yet)
function owt_lib_ajax_handler_fn()
{
$param = isset($_REQUEST[ 'param' ]) ? trim($_REQUEST[ 'param' ]) : "";
if ( ! empty($param) ){
if ( $param == "get_all_posts" ){
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 66 ],
];
$all_posts = new WP_Query($args);
$json_response = [];
if ( $all_posts->have_posts() ){
while ( $all_posts->have_posts() ) {
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields(get_the_ID()),
],
];
}
wp_send_json($json_response, 200);
wp_die();
}
else {
wp_send_json($json_response, 404);
wp_die();
}
}
}
wp_die();
}
please have a look as below:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => array('red', 'orange'),
'compare' => 'IN',
),
array(
'key' => 'featured',
'value' => '1',
'compare' => '=',
),
),
));
Please use below function:
add_action("wp_ajax_owt_ajax_lib", "owt_ajax_lib");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_ajax_lib");
function owt_ajax_lib() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 33 ],
];
$all_posts = new WP_Query($args);
$json_response = array();
if ( $all_posts->have_posts() ):
while ( $all_posts->have_posts() ) : $all_posts->the_post();
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields( get_the_ID() ),
],
];
endwhile;
endif;
echo json_encode($json_response);
die;
}
}
die;
}

Yii2 uploadfile image from model method beforeSave

i try to upload 4 or less images, the ajax validation do not return any error, but on submit i get the follow:
"errors": {
"imageFiles": [
"Please upload a file."
]
}
attr:
/**
* #var UploadedFile[]
*/
public $imageFiles;
Rules:
return [
[['imageFiles'], 'required', 'on' => self::REPORT_STEP1],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 4],
];
BeforeSave:
public function beforeSave($insert)
{
$files_urls = [];
$this->imageFiles = UploadedFile::getInstances($this, 'imageFiles');
foreach ($this->imageFiles as $file) {
$path = Url::to(['/uploads/reports/'], true) . Yii::$app->security->generateRandomString() . '.' . $file->extension;
$file->saveAs($path);
$files_urls[] = $file->name;
}
$this->img_url = json_encode($files_urls);
return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
Form:
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
'options' => [
'enctype' => 'multipart/form-data'
]
]) ?>
<?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<div class="form-group">
<?= Html::submitButton('Siguiente', ['class' => 'btn btn-standard']) ?>
</div>
<?php ActiveForm::end() ?>

Yii2 unique validator ignored

In the rules() of my RegisterForm model:
[ 'user_username', 'unique', 'targetClass' => 'app\models\User', 'message' => 'This username is already been taken.' ],
In my controller:
$model = new RegisterForm();
if ( $model->load( Yii::$app->request->post() ) ) {
if ( $user = $model->register() ) {
return $this->redirect( [ '/login' ] );
}
}
In RegisterForm:
public function register() {
$user = new User();
$user->user_firstname = $this->user_firstname;
$user->user_lastname = $this->user_lastname;
$user->user_username = $this->user_username;
$user->user_email = $this->user_email;
$user->setPassword( $this->user_password );
if ( !$user->validate() ) {
return null;
}
if ( $user->save() ) {
return $user;
}
return null;
}
Form:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field( $model, 'user_firstname' )->textInput( [ 'maxlength' => true ] ) ?>
<?= $form->field( $model, 'user_lastname' )->textInput( [ 'maxlength' => true ] ) ?>
<?= $form->field( $model, 'user_username' )->textInput( [ 'maxlength' => true ] ) ?>
<?= $form->field( $model, 'user_email' )->textInput( [ 'maxlength' => true ] ) ?>
<?= $form->field( $model, 'user_password' )->passwordInput() ?>
<?= $form->field( $model, 'user_password_repeat' )->passwordInput() ?>
<?= Html::submitButton( 'Register', [ 'class' => 'btn btn-primary', 'name' => 'register-button' ] ) ?>
<?php ActiveForm::end(); ?>
Yet when I enter a username that I know already exists, the error never comes up and the record tries to save, though I get: Integrity constraint violation: 1062 Duplicate entry ...
EDIT: if I add the unique rule to the User model itself the form will not submit if I input a username that exists, the errors just don't show up
Like I have suspected, you are not checking for unique user_username attribute in client side. The reason why it's not working it's because you are not sending Ajax requests to check the results from database. Unlike other rules, unique rule requires additional Ajax requests to server since it would be pretty bad thing if Javascript would retrieve all currently registered username and store somewhere in Client side.
To solve you problem, in form write something like this:
$form = ActiveForm::begin([
'enableAjaxValidation' => true,
'validationUrl' => [<URL HERE>],
]);
Now you have to create a method (action) in controller that returns validation (not just unique, all of them) back to ActiveForm. So it could be something like this:
public function actionAjaxValidation()
{
$post = Yii::$app->request->post();
$model = new YourClass();
if (!$model->load($post)) {
throw new HttpException(403, 'Cannot load model');
}
$array = ActiveForm::validate($model);
return json_encode($array);
}