Can't create object in the controller Yii2 - yii2

I am trying to create on instace of ProductReview which has CRUD and model and database tabel but i get an empty object. I tried whit other models but they all work as expected. Can you give an advance ?
This is what i got in controller:
$review = new ProductReview();
var_dump($review);die;
wich returns:
object(backend\modules\products\models\ProductReview)#322 (8) { ["_attributes":"yii\db\BaseActiveRecord":private]=> array(0) { } ["_oldAttributes":"yii\db\BaseActiveRecord":private]=> NULL ["_related":"yii\db\BaseActiveRecord":private]=> array(0) { } ["_errors":"yii\base\Model":private]=> NULL ["_validators":"yii\base\Model":private]=> NULL ["_scenario":"yii\base\Model":private]=> string(7) "default" ["_events":"yii\base\Component":private]=> array(0) { } ["_behaviors":"yii\base\Component":private]=> array(0) { } }
And because of that i get an error in my ActiveForm which is:
Call to a member function isAttributeRequired() on string
Why is that happens and why is it happens only with ProductReview? Do you guys have a clue?Thank you!
EDIT
Model:
<?php
namespace backend\modules\products\models;
use Yii;
use backend\modules\products\models\Product;
/**
* This is the model class for table "product_review".
*
* #property integer $id
* #property integer $product_id
* #property integer $user_id
* #property integer $active
* #property string $language
* #property string $names
* #property string $email
* #property string $title
* #property string $review
* #property integer $rating
* #property string $dt
*/
class ProductReview extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'product_review';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['product_id', 'language', 'names', 'review', 'rating'], 'required'],
[['product_id', 'user_id', 'active', 'rating', 'is_home', 'status'], 'integer'],
[['review'], 'string'],
[['dt'], 'safe'],
[['language'], 'string', 'max' => 10],
[['names', 'title'], 'string', 'max' => 255],
[['email'], 'string', 'max' => 100],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'product_id' => Yii::t('app', 'Product'),
'user_id' => Yii::t('app', 'Customer'),
'active' => Yii::t('app', 'Active'),
'language' => Yii::t('app', 'Language'),
'names' => Yii::t('app', 'Names'),
'email' => Yii::t('app', 'Email'),
'title' => Yii::t('app', 'Title'),
'review' => Yii::t('app', 'Review'),
'rating' => Yii::t('app', 'Rating'),
'dt' => Yii::t('app', 'Date'),
'is_home' => Yii::t('app', 'home'),
];
}
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getProduct()
{
return $this->hasOne(Product::className(), ['id' => 'product_id']);
}
public function changeActiveForm() {
$active = "";
if ($this->active == 1) {
$active = 'checked="checked"';
}
return '<label class="switchery switchery-default taCenter">
<input type="checkbox" class="js-switch" data-color="#99d683" data-secondary-color="#f96262" value="1" id="check_' . $this->id . '" name="field_types" class="legend-switch" ' . $active . ' onchange="changeStatusActive(' . $this->id . ', \'product-review\');"></input>
<label data-off="'.Yii::t('app', 'Не').'" data-on="'.Yii::t('app', 'Да').'" for="check_' . $this->id . '"></label>
<span></span>
</label>';
}
public function changeHome() {
$active = "";
if ($this->is_home == 1) {
$active = 'checked="checked"';
}
return '<label class="switchery switchery-default taCenter">
<input type="checkbox" class="js-switch" data-color="#99d683" data-secondary-color="#f96262" value="1" id="checkH_' . $this->id . '" name="field_types" class="legend-switch" ' . $active . ' onchange="changeHome(' . $this->id . ', \'product-review\');"></input>
<label data-off="'.Yii::t('app', 'Не').'" data-on="'.Yii::t('app', 'Да').'" for="checkH_' . $this->id . '"></label>
<span></span>
</label>';
}
public function changeStatus() {
$active = "";
if ($this->status == 1) {
$active = 'checked="checked"';
}
return '<label class="switchery switchery-default taCenter">
<input type="checkbox" class="js-switch" data-color="#99d683" data-secondary-color="#f96262" value="1" id="checkS_' . $this->id . '" name="field_types" class="legend-switch" ' . $active . ' onchange="changeStatus(' . $this->id . ', \'product-review\');"></input>
<label data-off="'.Yii::t('app', 'Не').'" data-on="'.Yii::t('app', 'Да').'" for="checkS_' . $this->id . '"></label>
<span></span>
</label>';
}
public function getUserList() { // could be a static func as well
$users = User::find()->all();
$arrayUsers = array();
if($users){
foreach($users as $user){
$arrayUsers[$user->id] = $user->username;
}
}
return $arrayUsers;
}
public function getProductList() { // could be a static func as well
$products = Product::find()->all();
$arrayProducts = array();
if($products){
foreach($products as $product){
$arrayProducts[$product->id] = $product->title;
}
}
return $arrayProducts;
}
public function showRating() {
$rating = $this->rating;
$ratingHTML = '';
$ratingHTML .= '<ul class="ratingList">';
$ratingHTML .= ($rating >= 1) ? '<li class="active">': '<li>';
$ratingHTML .= '<i class="fa fa-star-o empty tr_all_hover"></i>';
$ratingHTML .= '<i class="fa fa-star active tr_all_hover"></i>';
$ratingHTML .= '</li>';
$ratingHTML .= ($rating >= 2) ? '<li class="active">': '<li>';
$ratingHTML .= '<i class="fa fa-star-o empty tr_all_hover"></i>';
$ratingHTML .= '<i class="fa fa-star active tr_all_hover"></i>';
$ratingHTML .= '</li>';
$ratingHTML .= ($rating >= 3) ? '<li class="active">': '<li>';
$ratingHTML .= '<i class="fa fa-star-o empty tr_all_hover"></i>';
$ratingHTML .= '<i class="fa fa-star active tr_all_hover"></i>';
$ratingHTML .= '</li>';
$ratingHTML .= ($rating >= 4) ? '<li class="active">': '<li>';
$ratingHTML .= '<i class="fa fa-star-o empty tr_all_hover"></i>';
$ratingHTML .= '<i class="fa fa-star active tr_all_hover"></i>';
$ratingHTML .= '</li>';
$ratingHTML .= ($rating >= 5) ? '<li class="active">': '<li>';
$ratingHTML .= '<i class="fa fa-star-o empty tr_all_hover"></i>';
$ratingHTML .= '<i class="fa fa-star active tr_all_hover"></i>';
$ratingHTML .= '</li>';
return $ratingHTML;
}
}

Related

An error occurred while creating the inverse form: Call to a member function isAttributeRequired() on null?

please help me deal with this problem, after creating the inverse form on yii2, this error occurred:
Call to a member function isAttributeRequired() on null
1. in C:\Users\acer\OSPanel\domains\medicalyii2\vendor\yiisoft\yii2\widgets\ActiveField.php at line
/**
* Adds aria attributes to the input options.
* #param $options array input options
* #since 2.0.11
*/
protected function addAriaAttributes(&$options)
{
if ($this->addAriaAttributes) {
if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) {
$options['aria-required'] = 'true';
}
if (!isset($options['aria-invalid'])) {
if ($this->model->hasErrors($this->attribute)) {
$options['aria-invalid'] = 'true';
}
}
}
}
2. yii\base\ErrorHandler::handleFatalError()
I can not understand what this problem is connected with .... This is how my form looks in the view:
<?php
$form = ActiveForm::begin([
'id' => 'appointment_form',
'fieldConfig' => [
'options' => [
'tag' => 'span',
'class' => 'input input--kohana'
],
'template' => '{input}{label}',
'inputOptions' => ['class' => 'input__field input__field--kohana'],
'labelOptions' => [
'class' => 'input__label input__label--kohana',
]
]
]);
?>
<?= $form->field($model, 'name')->textInput(['inputOptions' => ['id' => 'input-29']])->label("<i class=\"icon-phone5 icon icon--kohana\"></i><span class=\"input__label-content input__label-content--kohana\">" . $model->getAttributeLabel('Your Name') . "</span>") ?>
<?= $form->field($model, 'email')->textInput(['inputOptions' => ['id' => 'input-30']])->label("<i class=\"icon-dollar icon icon--kohana\"></i><span class=\"input__label-content input__label-content--kohana\">" . $model->getAttributeLabel('Email Address') . "</span>") ?>
<span class="last"><?= $form->field($model, 'phone')->textInput(['inputOptions' => ['id' => 'input-31']])->label("<i class=\"icon-phone5 icon icon--kohana\"></i><span class=\"input__label-content input__label-content--kohana\">" . $model->getAttributeLabel('Phone Number') . "</span>") ?></span>
<?= $form->field($model, 'date')->textInput(['inputOptions' => ['id' => 'datepicker']])->label(false) ?>
<!-- ОСТАЛЬНЫЕ ПОЛЯ ФОРМЫ -->
<?= $form->field($model, 'body')->textInput(['inputOptions' => ['id' => 'texterea']])->label("<i class=\"icon-new-message icon icon--kohana\"></i><span class=\"input__label-content input__label-content--kohana\">" . $model->getAttributeLabel('Message') . "</span>") ?>
<?= Html::submitButton('Submit'); ?>
<?php
ActiveForm::end();
?>
Controller:
public function actionIndex()
{
/* Создаем экземпляр класса */
$model = new AppointmentForm();
/* получаем данные из формы и запускаем функцию отправки contact, если все хорошо, выводим сообщение об удачной отправке сообщения на почту */
if ($model->load(Yii::$app->request->post()) && $model->appointment(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
/* иначе выводим форму обратной связи */
} else {
return $this->render('index');
}
}
AppointmentForm.php Model
class AppointmentForm extends Model
{
public $name;
public $email;
public $phone;
public $date;
public $body;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
// name, email, subject and body are required
[['name', 'email', 'phone', 'date', 'body'], 'required'],
// email has to be a valid email address
['email', 'email'],
];
}
/**
* Sends an email to the specified email address using the information collected by this model.
* #param string $email the target email address
* #return bool whether the model passes validation
*/
public function appointment($email)
{
$content = "<p>Email: " . $this->email . "</p>";
$content .= "<p>Name: " . $this->name . "</p>";
$content .= "<p>Phone: " . $this->phone . "</p>";
$content .= "<p>Date: " . $this->date . "</p>";
$content .= "<p>Body: " . $this->body . "</p>";
if ($this->validate()) {
Yii::$app->mailer->compose("#app/mail/layouts/html", ["content" => $content])
//->setTo($email)
->setTo('swallowsveta97#yandex.ru')
->setFrom([\Yii::$app->params['supportEmail'] => $this->name])
//->setFrom([$this->email => $this->name])
//->setFrom('swallowsveta97#yandex.ru')
//->setFrom([\Yii::$app->params['supportEmail'] => $this->name])
->setPhone($this->phone)
->setDate($this->date)
->setTextBody($this->body)
->send();
return true;
}
return false;
}
}
I was searching for internet on the Internet for 2 days, but I never found it.
Please tell me if this error may be related?
You should pass the model to the view
return $this->render('index', ['model'=> $model ,]);
eg:
public function actionIndex()
{
/* Создаем экземпляр класса */
$model = new AppointmentForm();
/* получаем данные из формы и запускаем функцию отправки contact, если все хорошо, выводим сообщение об удачной отправке сообщения на почту */
if ($model->load(Yii::$app->request->post()) && $model->appointment(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
/* иначе выводим форму обратной связи */
} else {
return $this->render('index', ['model'=> $model,]);
}
}

how to show latest posts from each category in drop down menu

I have added a drop down menu to my wordpress theme. I've got it installed and it works fine. However, now I would like to display the latest posts from each category in drop down menu. Can anyone help point me in the right direction.
an example of what I'm looking for
Here is the current code of my drop down menu
class CSS_Menu_Walker extends Walker {
var $db_fields = array('parent' => 'menu_item_parent', 'id' => 'db_id');
function start_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul>\n";
}
function end_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul>\n";
}
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
global $wp_query;
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$class_names = $value = '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
/* Add active class */
if (in_array('current-menu-item', $classes)) {
$classes[] = 'active';
unset($classes['current-menu-item']);
}
/* Check for children */
$children = get_posts(array('post_type' => 'nav_menu_item', 'nopaging' => true, 'numberposts' => 1, 'meta_key' => '_menu_item_menu_item_parent', 'meta_value' => $item->ID));
if (!empty($children)) {
$classes[] = 'has-sub';
}
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
$class_names = $class_names ? ' class="' . esc_attr($class_names) . '"' : '';
$id = apply_filters('nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args);
$id = $id ? ' id="' . esc_attr($id) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$attributes = ! empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) .'"' : '';
$attributes .= ! empty($item->target) ? ' target="' . esc_attr($item->target ) .'"' : '';
$attributes .= ! empty($item->xfn) ? ' rel="' . esc_attr($item->xfn ) .'"' : '';
$attributes .= ! empty($item->url) ? ' href="' . esc_attr($item->url ) .'"' : '';
$item_output = $args->before;
$item_output .= '<a'. $attributes .'><span>';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$item_output .= '</span></a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
function end_el(&$output, $item, $depth = 0, $args = array()) {
$output .= "</li>\n";
}
}
This method uses the built-in wp_get_recent_posts function. All you need to do is copy and paste the following code in your theme’s functions.php file or a site-specific plugin.
function wpb_recentposts_dropdown() {
$string .= '<select id="rpdropdown">
<option value="" selected>Select a Post<option>';
$args = array( 'numberposts' => '5', 'post_status' => 'publish' );
$recent_posts = wp_get_recent_posts($args);
foreach( $recent_posts as $recent ){
$string .= '<option value="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</option> ';
}
$string .= '</select>
<script type="text/javascript"> var urlmenu = document.getElementById( "rpdropdown" ); urlmenu.onchange = function() {
window.open( this.options[ this.selectedIndex ].value, "_self" );
};
</script>';
return $string;
}
add_shortcode('rp_dropdown', 'wpb_recentposts_dropdown');
add_filter('widget_text','do_shortcode');

Yii2 ActiveForm radioList required value verification

I implented a form using the Yii2 activeForm field, but can't get the form to submit. I keep getting the verification error "Payment Method cannot be blank" from the model, I set the payment method as a required value, but somehow the value from the radioList doesn't get to the model's payment_method attribute.
Model:
class OrderFormModel extends Model
{
public $total;
public $extra;
public $admin_message;
public $is_taxed;
public $alt_email;
public $payment_method;
public $alt_address;
public $address;
public $attachment;
public $lat;
public $lon;
const PAY_CREDIT = 1;
const PAY_CHEQUE = 2;
public static function getPaymentMethods()
{
return[
self::PAY_CREDIT => 'Pay Via Credit Card',
self::PAY_CHEQUE => 'Pay Via Cheque / Interac'
];
}
public function rules()
{
return
[
[['total', 'extra'], 'number'],
[['admin_message'], 'string', 'max' => 1000],
[['is_taxed'], 'integer'],
['alt_email', 'email'],
[['payment_method'], 'integer'],
[['payment_method'], 'required'],
[['alt_address'], 'string', 'max' => 255],
['address', 'validateAddress','skipOnEmpty' => false, 'skipOnError' => false],
[['attachment'], 'file', 'extensions' => 'pdf, doc, docx, rtf, txt'],
[['lat','lon'], 'double']
];
}
}
View:
<div id="payment_method" style="margin-bottom: 5%">
<h2 style="text-align: center">Set Customer Payment Option</h2>
<div class="row">
<?= $form->field($orderForm,'payment_method')->radioList(OrderFormModel::getPaymentMethods(),
["class"=>"form-control", "id"=>"pymnt-method", "tag" => "false","required" => "true","onclick"=>"$('#orderDetails-payment_method').val( $('input:radio:checked').val() )",
"itemOptions" => ["class" => "radio"],
"item" => function($index, $label, $name, $checked, $value){
$return = '<div class="col-sm-6"><label class = "modal-radio">';
$return .= '<input type = "radio" name ="'. $name .'" value = "' . $value .'" tabindex = "3" >';
$return .= '<span style = "padding: 0.7em;"><b style="font-size: 1.8em;">' . ucwords($label) .'</b></span>';
$return .= '</label></div>';
return $return;
}]) ?>
</div>
</div>

How can I restore a MySQL database from CakePHP model cache?

in app\tmp\cache\models there is a file called:
myapp_cake_model_default_mydb_users
The contents are:
1446583948
a:14:{s:2:"id";a:6:{s:4:"type";s:7:"integer";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:11;s:8:"unsigned";b:0;s:3:"key";s:7:"primary";}s:8:"username";a:7:{s:4:"type";s:6:"string";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:255;s:3:"key";s:5:"index";s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:8:"password";a:6:{s:4:"type";s:6:"string";s:4:"null";b:1;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:17:"num_free_listings";a:5:{s:4:"type";s:7:"integer";s:4:"null";b:1;s:7:"default";s:1:"0";s:6:"length";i:2;s:8:"unsigned";b:0;}s:3:"pin";a:6:{s:4:"type";s:6:"string";s:4:"null";b:1;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:7:"is_ldap";a:4:{s:4:"type";s:7:"boolean";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:1;}s:13:"ldap_username";a:6:{s:4:"type";s:6:"string";s:4:"null";b:1;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:8:"fullname";a:6:{s:4:"type";s:6:"string";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:8:"group_id";a:5:{s:4:"type";s:7:"integer";s:4:"null";b:0;s:7:"default";s:1:"2";s:6:"length";i:11;s:8:"unsigned";b:0;}s:16:"password_changed";a:4:{s:4:"type";s:4:"date";s:4:"null";b:1;s:7:"default";N;s:6:"length";N;}s:10:"last_login";a:4:{s:4:"type";s:8:"datetime";s:4:"null";b:1;s:7:"default";N;s:6:"length";N;}s:6:"status";a:6:{s:4:"type";s:26:"enum('active','suspended')";s:4:"null";b:0;s:7:"default";s:6:"active";s:6:"length";i:9;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:7:"created";a:4:{s:4:"type";s:8:"datetime";s:4:"null";b:0;s:7:"default";N;s:6:"length";N;}s:8:"modified";a:4:{s:4:"type";s:8:"datetime";s:4:"null";b:0;s:7:"default";N;s:6:"length";N;}}
Can I convert this (serialized php?) to SQL and recreate my table, if so how? Many thanks in advance.
In PHP create a file:
<?php
class AppSchema extends CakeSchema {
public function before($event = array()) {
return true;
}
public function after($event = array()) {
}
$dir = 'files/';
$files = [
'table_names' => 'myapp_cake_model_default_mydb_tablenames',
];
foreach ($files as $table => $file){
$content = file(realpath( $dir.$file ));
$content = unserialize($content[1]);
$info = null;
foreach ($content as $field => $prop){
$info .= "'$field' => array(";
foreach ($prop as $key => $value){
$info .= "'$key' => ";
if($key == 'null'){
$info .= empty($value)?'false':'true';
}elseif($key == 'default'){
$info .= empty($value)?'null':"'$value'";
}elseif($key == 'unsigned'){
$info .= empty($value)?'false':'true';
}else{
$info .= empty($value)?"''":"'$value'";
}
$info .= ", ";
}
$info .= "),\n";
}
echo "public $".$table." = array(
".$info."'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB')
);\n\n";
}
?>
}
Then run it in the browser and you should get some code to paste a the schema.php file. Then use the Cake console to create the tables in the MySQL database.

Using add_filter() inside of WP_Widget::widget()

I'm developing a Widget. I want to show all posts' from the last 30 days. I'll use this snippet (from CODEX) :
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
// posts in the last 30 days
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );
Now this is my widget class :
class Okunma_Sayisina_Gore_Listele extends WP_Widget {
public function __construct() {
parent::__construct(
'okunma_sayisina_gore_listele', // Base ID
'Okunma_Sayisina_Gore_Listele', // Name
array( 'description' => 'Son n gün içinde yazılmış yazıları okunma sayılarına göre sıralayarak listeler', ) // Args
);
}
public function filter_where( $where = '' ) {
// posts in the last 30 days
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
public function widget( $args, $instance ) {
global $wpdb;
extract( $args );
$title = apply_filters( 'widget_title', $instance['title'] );
$n = intval($instance['n']);
echo $before_widget;
if ( ! empty( $title ) )
echo $before_title . $title . $after_title;
/* IT'S NOT WORKING */
add_filter( 'posts_where', array('this','filter_where') );
$posts = get_posts(array(
"number_posts" => $n,
"post_type" => "post",
));
remove_filter( 'posts_where', array('this','filter_where') );
foreach ($posts as $post)
{
echo $post->post_title;
}
echo $after_widget;
}
public function update( $new_instance, $old_instance ) {
...
}
public function form( $instance ) {
...
}
}
add_action( 'widgets_init', create_function( '', 'register_widget( "Okunma_Sayisina_Gore_Listele" );' ) );
Filter isn't working. This widget listing all post, not only from last 30 days.
Also, i tried
add_filter( 'posts_where', array('Okunma_Sayisina_Gore_Listele','filter_where') );
instead of
add_filter( 'posts_where', array('this','filter_where') );
but it is'nt not working, too.
OK, I found answer on Filter Reference . I forget 'suppress_filters' => FALSE .
$posts = get_posts(array(
"number_posts" => 4,
"post_type" => "post",
'suppress_filters' => FALSE
));