My pager doesn't change to chosen page. When I click to the next page button it reloads the page. I also tried without Pjax container but the result was the same. I red the other posts but still can't figure it out. What I am doing is :
$categoriesProvider = new ActiveDataProvider([
'query' => Page::find()->where(['enable' => 1, 'id_in' => $page_id])->orderBy('sort ASC'),
'pagination' => [
'pageSize' => 1,
'route' => "/".Yii::$app->getRequest()->getQueryParam('page')
]
]);
return $this->render('index', [
'categoriesProvider' => $categoriesProvider
]);
and in the view:
<?php Pjax::begin() ?>
<div class="content-area col-md-8 col-sm-6 col-xs-12 no-padding">
<?php if(!empty($categoriesProvider)){
echo ListView::widget([
'dataProvider' => $categoriesProvider,
'layout' => "{summary}\n{items}
\n<nav class='post-pagination col-md-12 col-sm-12 col-xs-12'>
{pager}
</nav>",
'itemView' => function($model, $key, $index, $widget){
return $this->render('_category', [
'model' => $model,
]);
},
'pager' => [
'nextPageLabel' => ">>",
'prevPageLabel' => "<<",
'maxButtonCount' => 5,
'options' => [
'tag' => 'ul',
'class' => 'pagination',
]
]
]);
}?>
</div><!-- Content Area /- -->
<?php Pjax::end(); ?>
URL configuration:
<?php
namespace frontend\controllers;
use backend\models\News;
use backend\models\Page;
use backend\models\Product;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
class SplitterController extends Controller
{
public function actionManageRequest()
{
$param_page = \Yii::$app->getRequest()->getQueryParam('page');
$param_category = \Yii::$app->getRequest()->getQueryParam('category');
$param_product = \Yii::$app->getRequest()->getQueryParam('product');
$page = $this->getModel($param_page, new Page());
//If page is existing page model go forward
if(!empty($page)){
$controller = $this->getController($page->view);
if($this->checkId($param_page) === 'news'){
$model = new News();
}else{
$model = new Page();
}
$category = $this->getModel($param_category, $model);
if(!empty($category)){
$product = $this->getModel($param_product, new Product());
//If product is existing product model - go forward to single view
if(!empty($product)){
$this->registerTags($product);
try{
return \Yii::$app->runAction("$controller/view");
}
catch (\Throwable $e){
throw new NotFoundHttpException('Page not found',404);
}
}
//If product is not empty and product don't - throw exception
if(!empty($param_product) && $product === null){
throw new NotFoundHttpException('Page out found', 404);
}
$this->registerTags($category);
//If page model is news page - render news single view
if($this->checkId($param_page) === 'news'){
return \Yii::$app->runAction("$controller/multi-view");
}
try{
return \Yii::$app->runAction("$controller/multi-view");
}
catch (\Throwable $e){
throw new NotFoundHttpException('Page not found',404);
}
}
$this->registerTags($page);
//If category is not empty but no such page found - throw exception
if(!empty($param_category) && $category === null){
throw new NotFoundHttpException('Page not found', 404);
}
return \Yii::$app->runAction($page->view);
}
//If page is not empty but no such page found - throw exception
if(!empty($param_page) && $page === null){
throw new NotFoundHttpException('Page not found', 404);
}
$page = Page::findOne(13);
$this->registerTags($page);
return \Yii::$app->runAction($page->view);
}
private function getModel($param, $model)
{
$chunks = explode('-', $param);
$chunk_id = end($chunks);
return $model::findOne($chunk_id);
}
private function registerMetaTags($name, $content)
{
\Yii::$app->view->registerMetaTag([
'name' => $name,
'content' => $content
]);
}
private function registerTitle($title)
{
\Yii::$app->view->title = $title;
}
private function checkId($param)
{
$id = explode('-', $param);
$id = end($id);
switch ($id) {
case 14:
return 'news';
break;
default:
return 'page';
break;
}
}
private function getController($path)
{
$controller = explode('/', $path);
return $controller[0];
}
private function registerTags($model)
{
$this->registerMetaTags('description', $model->meta_title);
$this->registerTitle($model->meta_title);
}
}
Url manager rules :
'rules' => [
'<page>/<category>/<product>' => 'splitter/manage-request',
'<page>/<category>' => 'splitter/manage-request',
'<page>' => 'splitter/manage-request',
'' => 'splitter/manage-request'
],
It looks like Pagination param conflict with your URL rules. Pagination uses page GET param to store current page number in URL. But your rules also uses page param and overrides param used by Pagination. You should use different param in your pagination config, to avoid conflicts:
'pagination' => [
'pageSize' => 1,
'route' => "/".Yii::$app->getRequest()->getQueryParam('page'),
'pageParam' => 'paginationPage',
]
See https://www.yiiframework.com/doc/api/2.0/yii-data-pagination#$pageParam-detail
Or you can rename params in your rules to avoid such problem also in other places:
'rules' => [
'<r_page>/<r_category>/<r_product>' => 'splitter/manage-request',
'<r_page>/<r_category>' => 'splitter/manage-request',
'<r_page>' => 'splitter/manage-request',
'' => 'splitter/manage-request'
],
Related
E/App: Got error:
java.lang.IllegalArgumentException: Invalid Setup Intent client secret: pi_3LtYhHAZTS98jCaY3NVtpCAW_secret_yUvzN3ytPIexEVJGtOzvQCSOM
at com.stripe.android.model.SetupIntent$ClientSecret.
Here i added my all codes of java class and php api for the test but i got this above error on the same code so plz do my help
paymentSheet = new PaymentSheet(this, this::onPaymentSheetResult);
Fuel.INSTANCE.post("my api link",null).responseString(new Handler<String>() {
#Override
public void success(String s) {
try {
final JSONObject result = new JSONObject(s);
customerConfig = new PaymentSheet.CustomerConfiguration(
result.getString("customer"),
result.getString("ephemeralKey")
);
paymentIntentClientSecret = result.getString("paymentIntent");
PaymentConfiguration.init(getContext().getApplicationContext(), result.getString("publishableKey"));
} catch (JSONException e) { /* handle error */ }
}
#Override
public void failure(#NotNull FuelError fuelError) { /* handle error */ }
});
if(isset($action) && $action='pay' && isset($amount)){
\Stripe\Stripe::setApiKey('sk_test_qrdTKAz2kaeZEPZHK2OdrNpn');
// Use an existing Customer ID if this is a returning customer.
$userid = $_GET['u'];
$query_usr = "SELECT * FROM tbl_user WHERE user_id = '$userid'";
$r_usr = $conn->query($query_usr);
$user = $r_usr->fetch_assoc();
if($user['stripe_customer'] == NULL){
$customer = \Stripe\Customer::create([
'name' => $user['user_name'],
'email' => $user['user_email']
]);
$customer_id = $customer->id;
$conn->query("UPDATE tbl_user SET stripe_customer = '$customer_id' WHERE user_id = $userid");
}
else{
$customer_id = $user['stripe_customer'];
}
$ephemeralKey = \Stripe\EphemeralKey::create(
[
'customer' => $customer_id,
],
[
'stripe_version' => '2020-08-27',
]);
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => 1099,
'currency' => 'cad',
'customer' => $customer_id,
'automatic_payment_methods' => [
'enabled' => 'true',
],
]);
$si = \Stripe\SetupIntent::create([
'customer' => $customer_id
]);
$response['paymentIntent'] = $paymentIntent->client_secret;
$response['setupIntent'] = $si->client_secret;
$response['ephemeralKey']= $ephemeralKey->secret;
$response['customer']= $customer_id;
$response['publishableKey'] = 'pk_test_0aSL6prHXE16hsokTWYKk8Gz';
echo json_encode($response);
// return $response->withJson([
// 'paymentIntent' => $paymentIntent->client_secret,
// 'ephemeralKey' => $ephemeralKey->secret,
// 'customer' => $customer_id,
// 'publishableKey' => 'pk_live_8mBL0Iji2oVDpgmBAVwPiicC'
// ])->withStatus(200);
}
else
{
$response['error']=TRUE;
$response['error_msg']="Required Parameters are missing";
echo json_encode($response);
}
private void presentPaymentSheet() {
final PaymentSheet.Configuration configuration = new PaymentSheet.Configuration.Builder("!2min, Inc.")
.customer(customerConfig)
// Set `allowsDelayedPaymentMethods` to true if your business can handle payment methods
// that complete payment after a delay, like SEPA Debit and Sofort.
.allowsDelayedPaymentMethods(true).build();
paymentSheet.presentWithSetupIntent(
paymentIntentClientSecret,
configuration
);
}
private void onPaymentSheetResult(final PaymentSheetResult paymentSheetResult) {
if (paymentSheetResult instanceof PaymentSheetResult.Canceled) {
Log.d("cantag","Canceled");
} else if (paymentSheetResult instanceof PaymentSheetResult.Failed) {
Log.e("App", "Got error: ", ((PaymentSheetResult.Failed) paymentSheetResult).getError());
} else if (paymentSheetResult instanceof PaymentSheetResult.Completed) {
// Display for example, an order confirmation screen
Log.d("tcmp","Completed");
}
}
Based off the error message, you should be passing in a SetupIntent's client_secret - a SetupIntent id starts with si_ . However, you're passing in a PaymentIntent's client_secret - a PaymentIntent id starts with pi_
If you intend to use a PaymentIntent, you should follow the guide here : https://stripe.com/docs/payments/accept-a-payment?platform=android
If you intend to use a SetupIntent, you should follow the guide here : https://stripe.com/docs/payments/save-and-reuse?platform=android&ui=payment-sheet
I can successfully import Excel Data in Laravel and Insert into Database multiple tables. I am using maatwebsite/excel version 3 composer package and laravel version 5.8
How can I insert mamber_id value in licence_application table (foreign id) which is member table primary id.
ImportClass file:
class UsersImport implements ToCollection
{
/**
* #param Collection $collection
*/
public function collection(Collection $rows)
{
foreach ($rows as $row){
Member::create([
'full_name' => $row[0],
'father_name' => $row[1],
'mother_name' => $row[2],
'cell_number' => $row[3],
]);
LicenceApplication::create([
'member_id' => ???
'licence_category_name' => $row[4],
]);
LicenceSuccess::create([
'application_type' => $row[5],
]);
}
}
}
Controller file: ImporExcelController.php
public function import(Request $request)
{
$this->validate($request, [
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::import(new UsersImport, $path);
return back()->with('success', 'Import data successfully!');
}
Excel file screenshot: https://imgur.com/a/XhxBRpW
Please help me how to solve this issue?
I solve this issue here is the code.
foreach ($rows as $row){
$memberId = Member::create([
'full_name' => $row['full_name'],
'father_name' => $row['father_name'],
'mother_name' => $row['mother_name'],
'cell_number' => $row['cell_number'],
]);
$applicationId = LicenceApplication::create([
'member_id' => $memberId->member_id,
'licence_category_name' => $row['licence_category_name'],
]);
LicenceSuccess::create([
'member_id' => $memberId->member_id,
'application_id' => $applicationId->application_id,
'application_type' => $row['application_type'],
]);
}
I have this action inside ProdutosController. It renders view2 that has an itemview pointing to _view2 which has a DetailView to show products.
public function actionView2()
{
$model = new Produtos();
$dataProvider = new ActiveDataProvider([
'query' => Produtos::find(),
'pagination' => false,
]);
// get the posts in the current page
$posts = $dataProvider->getModels();
// render
return $this->render('view2', [
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
the view2
<?php
use yii\helpers\Html;
use yii\widgets\ListView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model app\models\Atividades */
// $this->title = implode('', $cat);
?>
<div class="produtos-view2">
<?php
//use kartik\social\FacebookPlugin;
//echo FacebookPlugin::widget(['type'=>FacebookPlugin::SHARE, 'settings' `=> []]);`
?>
</div>
<?= ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_view2',
]); ?>
<br/><br/>
and the _view2 that as DetailView inside:
<?= DetailView::widget([
'model' => $model,
'options' => ['class' => 'detail1-galeria-view2'],
'attributes' => [
// cria um array com a fotografia, em que carrega a path no campo fieldName da bd
[
'attribute'=>'',
//'value'=>$model->foto,
'value'=>Html::a(Html::img(Yii::$app->getUrlManager()->getBaseUrl() . "/" .$model->foto, ['width'=>'192', 'height' => "256"]), $model->foto),
'format' => 'raw',
],
[
'attribute'=>'',
'value'=>$model->nome,
],
[
'attribute'=>'',
'value'=>$model->categoria,
],
[
'attribute'=>'',
'value'=>$model->descricao,
],
[
'attribute'=>'',
'value'=>$model->valor.' '.'€',
],
// info
[
'attribute'=>'',
'format' => 'raw',
'value'=> Html::a(Yii::t('app','Comprar'), Url::toRoute(['contacto/create2'])),
],
],
]) ?>
In another project i was able to make a search box in _view2 by render _search.php inside it and by modifying the ProdutosSearch model. But this was achieved with a GridView that accepts $dataprovider and $searchModel directly inside the widget.
Now in my new project, i'm trying hard to make a search input box to filter what the DetailView shows (it shows the foto, name, category, etc... of products) but cannot do it because the detail view doesn't accept $dataProvider data.
How can i solve this and make a products gallery with search box using a DetailView.
EDIT
Controller action:
public function actionMySearchFunction()
{
$model = new Produtos();
$searchModel = new CategoriasSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider = new ActiveDataProvider([
'query' => Produtos::find(),
'pagination' => false,
]);
// get the posts in the current page
$posts = $dataProvider->getModels();
// render
return $this->render('view2', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'model' => $model,
]);
}
MySearchFunction.php
<?php
public function MySearchFunction()
{
$post = Yii::$app->request->post();
if (!empty($post)){
$postParam1 = $post['categoria']; // get the value ffrom the filter field submitted)
$query = ProdutosSearch::find()->where(['categoria' => $postParam1]);
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => $query,
]);
$dataProvider->pagination->pageSize=15;
return $this->render('view2', [
'dataProvider' => $dataProvider,
]);
}
}
?>
VIEW2
<?php $form = ActiveForm::begin([
'action' => Url::to(['/produtos/my-search-function']),
'method' => 'get',
'options' => ['class' => 'form-inline form-group form-group-sm col-xs-12'],
'fieldConfig' => [
'template' => "{input}",
],
]); ?>
</div>
<?php echo var_dump(Url::to(['/produtos/my-search-function'])); ?>
<!--<nobr><?= $form->field($model, 'nome')->textInput(['placeholder' => 'Nome']) ?>-->
<nobr>
<?= $form->field($searchModel, 'categoria')->dropDownList(ArrayHelper::map(Categorias::find()->all(), 'categoria','categoria'), ['prompt'=>Yii::t('yii', 'Escolha a categoria...')]) ?>
<?= Html::submitButton(Yii::t('app', 'Pesquisar'), ['class' => 'btn btn-warning']) ?>
</nobr>
<?php ActiveForm::end(); ?>
<div class="user-view">
<?= ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_view2',
]); ?>
<br/><br/>
</div>
You can easily add the fields you need in an action from section inside the view,
the search button submit the value to an action you use for search and the you can redirect the resulto to the controller you need.
In the action Form you can set the target controller/action. In this way pressing the submit botton the value in the submitted the the controller/action you have eg:
public function actionMySearchFunction()
{
$post = Yii::$app->request->post();
if (!empty($post)){
$postParam1 = $post['name_field_Filter1']; // get the value ffrom the filter field submitted)
$postParam2 = $post['name_field_Filter2'];
$query = YourModel::find()->where(['field1' => $postParam1, 'field2' => $postParam2]);
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => $query,
]);
$dataProvider->pagination->pageSize=15;
return $this->render('your_view', [
'dataProvider' => $dataProvider,
]);
}
}
first add search box on that page :
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $form yii\widgets\ActiveForm */
?>
<div class="student-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($searchModel, 'nome') ?>
<?= $form->field($searchModel, 'categoria') ?>
<div class="form-group">
<?= Html::submitButton('Apply', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
then in model prepare a filter method.
public function rules()
{
return [
['nome', 'string'],
['categoria', 'string'],
];
}
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
public function search($params)
{
$query = Produtos::find();
$dataProvider = new ActiveDataProvider(['query' => $query]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere(['like', 'nome', $this->nome])
->andFilterWhere(['like', 'categoria', $this->categoria]);
return $dataProvider;
}
I am trying to modify the find() method inside the model search and it throws an error "The data provider property must be set".
Here is my search model:
public function search($params)
{
$userID = Yii::$app->user->identity->id;
$groups = GroupAccess::find()
->where(['user_id' => $userID, 'item_name' => 'group_creator'])
->asArray()
->all();
foreach ($groups as $group) {
$accessGroups[] = $group['group_id'];
}
$query = Group::find($accessGroups);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'status_id' => $this->status_id,
//'created_user_id' => $this->created_user_id,
'created_date' => $this->created_date,
'profile_updated_user_id' => $this->profile_updated_user_id,
'profile_updated_date' => $this->profile_updated_date,
'last_accessed_user_id' => $this->last_accessed_user_id,
'last_accessed_date' => $this->last_accessed_date,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'description', $this->description]);
return $dataProvider;
}
And here is my controller action:
$searchModel = new GroupSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if (Yii::$app->request->isPjax) {
return $this->renderAjax('groups', [
'searchModel' => $searchModel,
'dataProviderMine' => $dataProvider,
]);
} else {
return $this->render('groups', [
'searchModel' => $searchModel,
'dataProviderMine' => $dataProvider,
]);
}
}
It is important to refine the query as the user should be able to see other groups.
How can i modify the find() method properly?
Thanks.
I see two bugs here:
Your find method
$query = Group::find($accessGroups)
will not work - just replace it with
$query = Group::find()->where(['id' => $accessGroups]);
I guess "The data provider property must be set" error is caused by your view code. E.g. if you are using GridView, you should set its 'dataProvider' widget option:
GridView::widget([
'dataProvider' => $dataProviderMine,
'searchModel' => $searchModel,
'columns' => [
'id', 'status_id', 'created_date' // your view columns here
]
])
Consider also using sub queries in your search method:
$idAccessQuery = GroupAccess::find()
->where(['user_id' => $userID, 'item_name' => 'group_creator'])
->select('group_id');
$query = Group::find()->where([
'id' => $idAccessQuery
]);
Im using CakePHP 2.0
I have a Model for my Users which is very simple:
<?php
App::uses('Model', 'Model');
class User extends AppModel {
public $name = 'User';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
)
);
public function beforeSave(array $options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
?>
However I keep getting the following error:
Fatal Error: Class 'String' not found in /home/xxx/app/Model/User.php on line 27.
The error disappears if I comment the beforeSave function.
What am I missing?
Try changing:
public function beforeSave(array $options = array()) {
to
public function beforeSave($options = array()) {