Not able to submit form inside footer in Yii2 - yii

I've a subscribe newsletter form inside footer that display on all page. To do this I've created a subscriber widget like this:
SubscriberWidget.php
<?php
namespace frontend\components;
use Yii;
use yii\base\Widget;
use yii\helpers\Html;
use frontend\models\SubscribeNewsletterForm;
class SubscriberWidget extends Widget
{
public function run()
{
$subscriber_model = new SubscribeNewsletterForm();
return $this->render('_subscribe-newsletter-form.php', [
'subscriber_model' => $subscriber_model
]);
}
}
?>
Here's the SubscribeNewsletterForm model code:
SubscribeNewsletterForm.php
<?php
namespace frontend\models;
use Yii;
use yii\base\Model;
class SubscribeNewsletterForm extends Model
{
public $email;
public function rules()
{
return [
[['email'], 'required'],
['email', 'email']
];
}
}
?>
Here is the code of my _subscribe-newsletter-form.php
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\Url;
?>
<h3>Subscribe to Newsletter</h3>
<?php $form = ActiveForm::begin(['id' => $subscriber_model->formName(), 'action' => ['project/subscriber'], 'validateOnBlur' => false, 'validateOnType' => false]); ?>
<div class="input-group">
<?= $form->field($subscriber_model, 'email')->textInput()->label(false); ?>
<span class="input-group-btn">
<?php echo Html::submitButton('Sign Up', ['class' => 'btn btn-primary subscribe-btn']); ?>
</span>
</div>
<?php ActiveForm::end(); ?>
<?php
$script = <<< JS
$('#{$subscriber_model->formName()}').on('beforeSubmit', function(e){
var form = $(this);
$.post(
form.attr("action"),
form.serialize()
).done(function(data){
form.trigger("reset");
})
return false;
});
JS;
$this->registerJs($script);
?>
Inside ProjectController.php I've created the action as follow:
public function actionSubscriber()
{
$subscriber_model = new SubscribeNewsletterForm();
$request = Yii::$app->request;
if($request->isAjax && $subscriber_model->load($request->post())){
$subscriber = new Subscriber([
'email' => $subscriber_model->email
]);
$subscriber->save();
}
}
Here's the Subscriber model code.
Subscriber.php
<?php
namespace frontend\models;
use yii\db\ActiveRecord;
class Subscriber extends ActiveRecord
{
public static function tableName()
{
return 'subscriber';
}
}
?>
frontend/config/main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
?>
With above code validation is working but i'm not able to save the email in database. Please tell what i'm doming wrong.

You need rules on your Model. Also, I always replace the generated tables names with the table prefix supported method. Also, I always like to use the Timestamp behavior to log when things are created or updated. Especially when your grabbing contact info for the use of leads, I would record the timestamps as well as their IP Address.
Subscriber.php
use yii\behaviors\TimestampBehavior;
// ...
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%subscriber}}';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\Subscriber', 'message' => 'This email address has already been taken.'],
[['created_at', 'updated_at'], 'integer'],
];
}

Related

Prestashop 1.7 - Bug FormBuilder on Cms Page Category

I wrote a Prestashop module to add two fields in the CMS Category but the render is wrong.
My source code:
<?php
class NewsSlider extends Module {
public function hookActionCmsPageCategoryFormBuilderModifier(array $params) {
$formBuilder = $params['form_builder'];
$locales = $this->get('prestashop.adapter.legacy.context')->getLanguages();
$formBuilder->add($this->name.'_cover_lang',
\PrestaShopBundle\Form\Admin\Type\TranslatableType::class,
[
'type' => \Symfony\Component\Form\Extension\Core\Type\FileType::class,
'label' => $this->l('Image de couverture'),
'options' => [
'required' => false,
'constraints' => [
'mimeTypes' => [
'image/png',
'image/jpeg'
],
'mimeTypesMessage' => 'JPEG/PNG',
]
],
'required' => false,
]
);
$formBuilder->add($this->name.'_header_lang',
\PrestaShopBundle\Form\Admin\Type\TranslateType::class,
[
'type' => \PrestaShopBundle\Form\Admin\Type\FormattedTextareaType::class,
'label' => $this->l('EntĂȘte de la page'),
'locales' => $locales,
'hideTabs' => false,
'required' => false
]
);
$languages = Language::getLanguages(true);
foreach($languages as $lang){
$content = $this->getCMSHeader($params['id'], $lang['id_lang'], $isCategory);
if(is_string($content) && strlen($content)) {
$params['data'][$this->name.'_header_lang'][$lang['id_lang']] = $content;
}
}
$formBuilder->setData($params['data']);
}
}
?>
You can see the render here.
And I wrote exactly the same code for the CMS Page (hookActionCmsPageFormBuilderModifier) and it's working. Why is it different?

SSL cake PHP form

I spent the site in https, I have 2 questions, the site is redirected but is it a 301 redirect? I did not write anything in the .htaccess file, how come the site is redirected in https?
I'm afraid of dupicate content.
The problem I have is that emails do not work anymore ...
here is the code:
public function initialize()
{
parent::initialize();
$this->loadComponent('Security', ['blackHoleCallback' => 'forceSSL']);
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'finder' => 'auth'
]
],
'loginAction' => ['controller' => 'Users', 'action' => 'login', 'prefix' => 'manager'],
'loginRedirect' => ['controller' => 'Pages', 'action' => 'index', 'prefix' => 'manager'],
'logoutRedirect' => ['controller' => 'Users', 'action' => 'login', 'prefix' => 'manager'],
// 'authorize' => 'Controller'
]);
}
public function forceSSL()
{
return $this->redirect('https://' . env('SERVER_NAME') . $this->request->here);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Security->requireSecure();
$this->checkManager();
$this->set('settings', Configure::read('Settings'));
}
Thank you
here is the solution:
public function initialize()
{
parent::initialize();
$this->loadComponent('Security', ['blackHoleCallback' => 'forceSSL']);
}
public function forceSSL()
{
return $this->redirect('https://' . env('SERVER_NAME') . $this->request->here);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Security->requireSecure();
$this->Security->config('unlockedActions', ['contact']);
}
AND :
Change statut in Controller.php
public function redirect($url, $status = 302)
Becomes :
public function redirect($url, $status = 301)

yii2 :why $model->image is empty after upload image with FileUploadUI

this is my _form.php :
<?php
use dosamigos\fileupload\FileUploadUI;
// with UI
?>
<?=
FileUploadUI::widget([
'model' => $model,
'attribute' => 'image',
'url' => ['media/upload', 'id' => 'image'],
'gallery' => false,
'fieldOptions' => [
'accept' => 'image/*'
],
'clientOptions' => [
'maxFileSize' => 200000
],
// ...
'clientEvents' => [
'fileuploaddone' => 'function(e, data) {
console.log(e);
console.log(data);
}',
'fileuploadfail' => 'function(e, data) {
console.log(e);
console.log(data);
}',
],
]);
?>
my file uploaded in my host but i need that url
this is my product controller and image is empty :
public function actionCreate()
{
$request = Yii::$app->request;
$model = new Product();
$idCon = Yii::$app->user->id;
$model->user_id = $idCon;
if ($request->isAjax)
{
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet)
{
return [
'title' => "Create new Product",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
else if ($model->load($request->post()) && $model->save())
{
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new Product",
'content' => '<span class="text-success">Create Product success</span>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
}
else
{
return [
'title' => "Create new Product",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
}
else
{
/*
* Process for non-ajax request
*/
if ($model->load($request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
}
}
and this is my model :
use Yii;
use yii\web\UploadedFile;
use yii\base\Model;
/**
* This is the model class for table "product".
*
* #property integer $id
* #property string $name
* #property string $price
* #property string $image
* #property string $url
* #property integer $user_id
*
* #property ConProduct[] $conProducts
* #property User $user
* #property Sales[] $sales
*/
class Product extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'product';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['price'], 'number'],
[['user_id'], 'integer'],
[['name', 'image'], 'string', 'max' => 300],
[['url'], 'string', 'max' => 255],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
how can i get image url with $model->image in controller !?
Have you tried to use yii\web\UploadedFile::getInstance()?
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->upload()) {
// do some stuff with file
}
http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html#wiring-up

Laravel 5.4 custom Auth::attempt always return false even my credential is true

I try to create auth::guard('profile') and using profiles table and Profile model but when I tried to do Auth::attempt($credential) it's always returning false even if my credentials is true.
Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('ProfileID');
$table->string('Name');
$table->string('UserId')->unique();
$table->string('Email')->unique();
$table->string('Password');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('profiles');
}
}
Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Profile extends Authenticatable
{
use Notifiable;
protected $fillable =
[
'Name', 'UserId', 'Email', 'Password'
];
public $timestamps = false;
protected $hidden =
[
'Password'
];
}
config\auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'profile' => [
'driver' => 'session',
'provider' => 'profiles'
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'profiles' => [
'driver' => 'eloquent',
'model' => App\Profile::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
ProfileController
public function postLogin(Request $r){
$credential = array(
'UserId' => $r->input('UserId'),
'Password' => $r->input('Password')
);
if(Auth::guard('profile')->attempt($credential)) {
echo "success";
}else{
Session::flash('error', 'Username or password is incorect');
return redirect('/');
}
}
Please help me, I cant find where the problem is.

Yii2 Invalid CAPTCHA action ID in module

I am getting the Invalid CAPTCHA action ID Exception in my custom contactus module. I managed to display the captcha but models validation rule throws the invalid action ID exception. Below is my code:
contactus/controllers/DefaultController.php
class DefaultController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'actions' => ['captcha','index'],
'allow' => true,
],
]
]
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(setting::ADMIN_EMAIL_ADDRESS)) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
} else {
return $this->render('index', [
'model' => $model,
]);
}
}
}
contactus/models/ContactForm.php
public function rules()
{
return [
// name, email, subject and body are required
[['name', 'email', 'subject', 'body','verifyCode'], 'required'],
// email has to be a valid email address
['email', 'email'],
// verifyCode needs to be entered correctly
['verifyCode', 'captcha','captchaAction'=>'default/captcha'],
];
}
contactus/views/default/index.php
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'subject') ?>
<?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'captchaAction' => 'default/captcha',
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end(); ?>
I get the below error:
Exception (Invalid Configuration) 'yii\base\InvalidConfigException' with message 'Invalid CAPTCHA action ID: default/captcha'in E:\wamp\www\yii-application\vendor\yiisoft\yii2\captcha\CaptchaValidator.php:81
Am I missing something?
You should modify your validation rule :
['verifyCode', 'captcha','captchaAction'=>'/contactus/default/captcha'],