I was given a project to update certain extensions and modules on without any documentation.
The issue I'm having is for one of the variables in the model, it is being regarded as not defined when using localhost (but works fine on the server version which is the exact same code).
From what I can see, it makes a single row in the database and assigns it a value of 1 or 0.
What could be causing this?
Keep in mind, this works fine on the server. I have turned global variables in my php.ini to On. No change. The Row is definitely created and exists in the database with a value. The page errors out after clicking "create new group".
Edit. Error message : Property "EventGroups.delegates_select_event_group " is not defined.
Code below is the model, controller and form. (and the options)
First off, the form view.
echo $form->switchGroup($model, 'delegates_select_event_group', array('class' => 'col-md-6'));
Model
public $delegates_select_event_group;
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name, description, guest_invites_per_user, delegates_select_event_group ', 'required'),
);
}
Options
//Options
// Event group selectable
const KEY_DELEGATES_SELECT_EVENT_GROUP = 'delegates_select_event_group';
public static function isDelegatesSelectEventGroup() {
return self::getValue(self::KEY_DELEGATES_SELECT_EVENT_GROUP, false);
}
public static function setDelegatesSelectEventGroup($value) {
return self::setValue(self::KEY_DELEGATES_SELECT_EVENT_GROUP, $value);
}
const KEY_DEFAULT_EVENT_GROUP_ID = 'default_event_group_id';
public static function getDefaultEventGroupID() {
$model = EventGroups::model()->find();
if ($model === null) {
return self::getValue(self::KEY_DEFAULT_EVENT_GROUP_ID, 1);
} else {
return self::getValue(self::KEY_DEFAULT_EVENT_GROUP_ID, $model->id);
}
}
public static function setDefaultEventGroupID($value) {
return self::setValue(self::KEY_DEFAULT_EVENT_GROUP_ID, $value);
}
Controller
public function actionCreate() {
$model = new EventGroups;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if (isset($_POST['EventGroups'])) {
$model->attributes = $_POST['EventGroups'];
if ($model->validate()) {
// Valid Save
$model->save(false);
$this->redirect(array('event/create'));
}
}
$this->render('create', array(
'model' => $model,
));
}
Related
I was able to use this to redirect to another route and pass data to it as well:
public function method() {
$dir = "A";
$name = "ABC";
return redirect()->route('catch')->with([
'dir' => $dir,
'name' => $name
]);
}
public function catch() {
dd(Session::has('dir'));
dd(Session::has('name'));
}
Above code was working until today
Then I tried setting session and checking within the method:
public function method() {
Session::put('dir', 'a');
Session::put('name', 'abc');
Session::has('dir'); // true
return redirect()->route('catch');
}
public function catch() {
Session::has('dir'); // false
}
(this works because of route Route::get('/catch', ['as' => 'catch', 'uses' => Controller#catch])...)
This was working until a second ago and I was messing up with nginx user permissions, then it stopped working
I'm completely lost as to why this is happening, and it happens about 50% of the time.
I have a check to see if a user exists by email and last name, and if they do, run some code. If the user doesn't exist, then create the user, and then run some code.
I've done various testing with dummy data, and even if a user doesn't exist, it first creates them, but then runs the code in the "if" block.
Here's what I have.
if (User::existsByEmailAndLastName($params->email, $params->lastName)) {
var_dump('user already exists');
} else {
User::createNew($params);
var_dump("Creating a new user...");
}
And here are the respective methods:
public static function existsByEmailAndLastName($email, $lastName) {
return User::find()->where([
'email' => $email,
])->andWhere([
'last_name' => $lastName
])->one();
}
public static function createNew($params) {
$user = new User;
$user->first_name = $params->firstName;
$user->last_name = $params->lastName;
$user->email = $params->email;
$user->address = $params->address;
$user->address_2 = $params->address_2;
$user->city = $params->city;
$user->province = $params->province;
$user->country = $params->country;
$user->phone = $params->phone;
$user->postal_code = $params->postal_code;
return $user->insert();
}
I've tried flushing the cache. I've tried it with raw SQL queries using Yii::$app->db->createCommand(), but nothing seems to be working. I'm totally stumped.
Does anyone know why it would first create the user, and then do the check in the if statement?
Editing with controller code:
public function actionComplete()
{
if (Yii::$app->basket->isEmpty()) {
return $this->redirect('basket', 302);
}
$guest = Yii::$app->request->get('guest');
$params = new CompletePaymentForm;
$post = Yii::$app->request->post();
if ($this->userInfo || $guest) {
if ($params->load($post) && $params->validate()) {
if (!User::isEmailValid($params->email)) {
throw new UserException('Please provide a valid email.');
}
if (!User::existsByEmailAndLastName($params->email, $params->lastName)) {
User::createNew($params);
echo "creating new user";
} else {
echo "user already exists";
}
}
return $this->render('complete', [
'model' => $completeDonationForm
]);
}
return $this->render('complete-login-or-guest');
}
Here's the answer after multiple tries:
Passing an 'ajaxParam' parameters with the ActiveForm widget to define the name of the GET parameter that will be sent if the request is an ajax request. I named my parameter "ajax".
Here's what the beginning of the ActiveForm looks like:
$form = ActiveForm::begin([
'id' => 'complete-form',
'ajaxParam' => 'ajax'
])
And then I added this check in my controller:
if (Yii::$app->request->get('ajax') || Yii::$app->request->isAjax) {
return false;
}
It was an ajax issue, so thanks a bunch to Yupik for pointing me towards it (accepting his answer since it lead me here).
You can put validation like below in your model:
public function rules() { return [ [['email'], 'functionName'], [['lastname'], 'functionforlastName'], ];}
public function functionName($attribute, $params) {
$usercheck=User::find()->where(['email' => $email])->one();
if($usercheck)
{
$this->addError($attribute, 'Email already exists!');
}
}
and create/apply same function for lastname.
put in form fields email and lastname => ['enableAjaxValidation' => true]
In Create function in controller
use yii\web\Response;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post()))
{
//place your code here
}
Add 'enableAjaxValidation' => false to your ActiveForm params in view. It happens because yii sends request to your action to validate this model, but it's not handled before your if statement.
I have a Yii form accept first name, last name and email from user. Using an add more link, users can add multiple rows of those three elements.
For email validation, unique and required are set in model rules and everything works fine. I am using JavaScript to create addition row on clicking add more link.
Problem
On the first row my values are John, Newman, johnnewman#gmail.com and the second row, i'm entering Mathew, Heyden, johnnewman#gmail.com. In this case email address is duplicated. None of the validation rules (require and unique) is capable of validating this. Can some one suggest a better method to validate this ?
Update:
I created a custom validation function and i guess this is enough to solve my problem. Can someone tell me how to access the whole form data / post data in a custom validation function ?
public function uniqueOnForm($attribute){
// This post data is not working
error_log($_REQUEST, true);
$this->addError($attribute, 'Sorry, email address shouldn\'t be repeated');
}
You can try this:
<?php
public function rules()
{
return array(
array('first_name', 'checkUser')
);
}
public function checkUser($attribute)
{
if($this->first_name == $this->other_first_name){
$this->addError($attribute, 'Please select another first name');
}
}
?>
You can also look into this extension
You can write custom validator:
//protected/extensions/validators
class UniqueMailValidator extends CValidator
{
/**
* #inheritdoc
*/
protected function validateAttribute($object, $attribute)
{
$record = YourModel::model()->findAllByAttributes(array('email' => $object->$attribute));
if ($record) {
$object->addError($attribute, 'Email are exists in db.');
}
}
}
// in your model
public function rules()
{
return array(
array('email', 'ext.validators.UniqueMailValidator'),
...
Or better try to use THIS
public function rules(){
return array(
//other rules
array('email', 'validEmail'),
)
}
public function validEmail($attribute, $params){
if(!empty($this->email) && is_array($this->email)){
$isduplicate = $this->isDuplicate($this->email);
if($isduplicate){
$this->addError('email', 'Email address must be unique!');
}
}
}
private function isDuplicate($arr){
if(count(array_unique($arr)) < count($arr)){
return true;
}
else {
return false;
}
}
because you are using tabular input (multiple row) , so make sure input field as an array. might be like this :
<?php echo $form->textField($model, 'email[]'); ?>
I got this code:
public function actionJoin() {
$user = new RUser;
if (isset($_POST['RUser']))
$user->attributes = $_POST['RUser'];
$this->render('join',
array(
'user' => $user
)
);
}
Which will not yet allow user to register. What I want to know is how to send data back to user. I mean, if user form haven't passed verification I have to send some data back, so there is no need for user to re-enter it again.
I can do so with this:
$user->mail = $_POST['RUser']['mail'];
But it's looks like dropping back to plain PHP and not using powers of the framework here.
Addition. Publishing RUser class, if needed:
class RUser extends CFormModel
{
public $mail;
public $alias;
public function safeAttributes()
{
return array(
'mail', 'alias'
);
}
}
Which version of Yii you use.
In Yii 1.1, there are no safeAttributes. You use the followings,
public function rules()
{
return array(
array('mail, alias', 'safe'),
);
}
I am new in YII framework. I am doing update operation using YII framework. I have controller with name sitecontroller.php, model jobseekerprofile.php, view personal.php.
I got the error:
Fatal error: Call to a member function isAttributeRequired() on a non-object in E:\wamp\www\yii\framework\web\helpers\CHtml.php on line 1414
My table is job_seeker_profile
Fields
1.id
2.user_id
3.contact_no
4.gender
5.dob
6.mstatus
7.address
8.location_id
I want to edit the data in contact_no and address according to user_id
Model-Jobseekerprofile.php - rules
public function rules()
{
return array(
array('contact_no,address','required'),
);
}
controller-Sitecontroller.php
class SiteController extends Controller {
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model=Jobseekerprofile::model()->find(array(
'select'=>'contact_no,address',"condition"=>"user_id=$user_id",
'limit'=>1,));
$model = Jobseekerprofile::model()->findByPk($user_id);
if(isset($_POST['Jobseekerprofile']))
{
$model->attributes=$_POST['Jobseekerprofile'];
if($model->save())
{
$this->redirect(array('profile','user_id'=>$model->user_id));
}
}
$this->render('personal',array('model' =>$model));
}
}
Anybody help me?
Seems that $model = Jobseekerprofile::model()->findByPk($user_id) is not finding anything, so $model is null, and that is why $model->isAttributeRequired() throws an error. Check your incoming params because of this and check if there a profile with such id (or maybe you should search by attributes instead of by id?).
Besides you can use
public function actionPersonal($id) {
$model = Jobseekerprofile::model()->findByPk($id);
//
}
Instead of
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
//
}
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['Jobseekerprofile']; //post key edited
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
}
First Check what you are getting in $_POST
and if all is ok then try to save like
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['jobseekerprofile'];
$model->contact_no= $_POST['Jobseekerprofile']['contact_no']; //post key edited
$model->address = $_POST['Jobseekerprofile']['address'];
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
if not work then check what model returns
$error=$model->getErrors();
print_r($error);
above code surely gives you idea why it is not saving