how to make adminEmail dynamically in yii framework - php

currently the adminEmail is set in the params.php file. I am trying to change the 'adminEmail' dynamically and then I can assign the email value I want. There is the code in the params.php.
return array(
// this is displayed in the header section
'title' => 'title here',
// this is admin email
'adminEmail' => 'admin#email.com',
But the admin emails can be more than one(eg. admin1#email.com, admin2#email.com), how can I set admin email dynamically in params.php ?
Thanks in advance!

You can try set multiple emails on adminEmail, and at runtime access it using index. E.G
//asign multiple email ids to adminEmail as array
'params'=>array(
// this is used in contact page
'adminEmail'=>array('webmaster#example.com','sany#gmail.com','xxx#yahoo.com','webmaster2#example.com')
),
//access it using array index at runtime as your requirement
<?php echo Yii::app()->params['adminEmail'][1];?> //sany#gmail.com
<?php echo Yii::app()->params['adminEmail'][2];?> // xxx#yahoo.com
OR
Create a static method on a class that will generate dynamic email ids and
then set it to your adminEmail param .e.g
class Email
{
public static function generateEmailIds()
{
//or any other way to generate email ids or id
return array('webmaster#example.com',
'sany#gmail.com',
'xxx#yahoo.com');
}
}
'params'=>array(
// this is used in contact page
'adminEmail'=>Email::generateEmailIds(),
)

Well, although I don't recommend this approach, what you want to do can be done like this:
You need to store your array in a file in serialized form (that is, call function serialize() on it. That will turn the array into a string.
You can read the file and unserialize it (that is, call function unserialize() on it. That will turn the string that you read form file back into a PHP array.)
$handle = fopen('path/to/file','rb');
$contents = fread($handle,999).
$array = unserialize($contents);
set 'adminEmail' to what you want it to be:
$array['adminEmail'] = 'new#email.com;
or even
$array['adminEmail']= array(..lots of emails..);
then you need to turn the array into a string and write the array back to file. Like this, for example:
$serialized_contents = serialize($array);
fwrite($handle, $serialized_contents);
There may be more efficient ways to do this if you want to.

Related

Using variable name in Laravel request object

I need to be able to loop through a list of laravel request variables and do something with them. I want to be able to use a variable when calling the request object so that I can run it in a loop instead of writing a line of code for every one.
For example, my text inputs may have names that look something like this
contact_main_name
contact_main_telephone
contact_main_email
contact_sub_name
contact_sub_telephone
contact_sub_email
contact_backup_name
contact_backup_telephone
contact_backup_email
In my request, I don't want to have to write
$request->contact_main_name
$request->contact_main_telephone
For each different type of contact I may have, I want to be able to loop through them like so
$contactTypes = [
'main',
'sub',
'backup',
'head'
];
foreach($contactTypes as $type){
//Start a new contact
$contact = new Contact;
$contact->type = $type;
$contact->name = $request->${"contact_".$type."_name"};
$contact->telephone = $request->${"contact_".$type."_telephone"};
$contact->email = $request->${"contact_".$type."_email"};
$contact->save();
}
How would i use a variable name when calling a laravel $request so that I can just build an array of possible types and loop through them all?
Note
I know i can edit the input fields themselves to look something like name="contact[type][name]" and then loop through them, but I cant be changing the input names, I have to do it via php in the controller itself.
As answered in comments, to do this, change the method of calling the input and use the actual input() function itself.
$contactTypes = [
'main',
'sub',
'backup',
'head'
];
foreach($contactTypes as $type){
//Start a new contact
$contact = new Contact;
$contact->type = $type;
$contact->name = $request->input("contact_".$type."_name");
$contact->telephone = $request->input("contact_".$type."_telephone");
$contact->email = $request->input("contact_".$type."_email");
$contact->save();
}
As an aside, you could also modify it slightly to use array indices matching the field names; this would allow you to add fields later by adding the appropriate field to the database and HTML without touching the code, and use array_keys() to retrieve the types submitted to allow seamless addition of types. As long as your validations are tight, this is probably the most automated way to allow future expansion...
Ex. Field Names:
contact[main][name]
contact[main][telephone]
...
contact[backup][email]
Ex. Code:
foreach(array_keys($request->input('contact')) as $type) {
$contact = Contact::create($request->input('contact.'.$type));
$contact->type = $type;
$contact->save();
}

how to replace text with another similar to mail merge?

I am working in Magento, and i have developed a module to send text messages to customers. In the settings of the module, the admin can set the message that will be sent to the customer. I'm trying to add a features that will allow the replacement of texts with data from my database.
for example, i currently have the following code that fetches the saved settings for the body of the text message:
$body = $settings['sms_notification_message'];
The message that is fetched looks like this:
Dear {{firstname}},
your order ({{ordernumber}}) has been shipped.
tracking#: {(trackingnumber}}
Thanks for your business!
{{storename}}
The goal is to have the module replace the variables in "{{ }}" with the customer and store information.
Unfortunately, i'm unable to figure out how to make it replace the information before sending the message. It is currently being send as is.
The easiest way to do it would be to use str_replace, like so:
// Set up the message
$message = <<< MESSAGE
Dear {{firstname}},
your order ({{ordernumber}}) has been shipped.
tracking#: {{trackingnumber}}
Thanks for your business!
{{storename}}
MESSAGE;
// Assign the values in an associative array
$values = [
'firstname' => 'firstnamevalue',
'ordernumber' => 'ordernumbervalue',
'trackingnumber' => 'trackingnumbervalue',
'storename' => 'storenamevalue'
];
// Create arrays $target indicating the value to change
$targets = [];
foreach ($values as $k => $v) {
$targets[] = '{{'.$k.'}}';
}
// Use str_replace to perform the substitution
echo str_replace($targets,$values,$message);

Yii can't access session variables

My problem: I can't access session data in the view, which I tried to save in the controller before rendering the view.
In my opinion there's an error when storing the session data. (It's necessary for me to modify the session data after creating it, not only in the single action.)
ProcessController.php
public function actionNew() {
$formhash = md5(time());
$hashList = array();
$hashList[$formhash]['processingNumber'] = '';
//fill with empty model
$hashList[$formhash]['model'] = $this->loadModel();
//store hashList in session
Yii::app()->session['hashList'] = $hashList;
$this->render('/process', array('hashValue => $formHash));
}
Now in the view I need the data from the session to show them to the user. But when dumping the hashList it just dumps "null" (Maybe because the saving in the controller didn't went well).
process.php
<?php
$form = this->beginWidget('CActiveForm', array(
'id' => 'process_form',
//several other things...
));
//Output: null
CVarDumper::dump(Yii::app()->session['hashList'],10,true);
?>
I tried to use $_SESSION instead of Yii::app()->session, which gives me access to the data in the view. But when handling other actions in the Controller the $_SESSION variable is undefined.
Any suggestions?
Thank you.
Long answer is:
Regarding to this documents:
$session=new CHttpSession;
$session->open();
$value1=$session['name1']; // get session variable 'name1'
$value2=$session['name2']; // get session variable 'name2'
foreach($session as $name=>$value) // traverse all session variables
$session['name3']=$value3; // set session variable 'name3'
You can use as well:
Yii::app()->session->set('hashList', $hashList);
Yii::app()->session->get('hashList');
And set it again.
Beside this session thing, why do not you use this:
$this->render('/process', array('hashValue => $formHash, 'hashList' => $hashList));
So you do not need to save it in a session if you can reach it directly into the view.
According to the documentation your code should work. An alternative might be to use the following, but it does the same:
Yii::app()->session->add('hashList', $hashList); // set the value
$hashList = Yii::app()->session->get('hashList'); // get the value
I expect the problem either a debugging problem, meaning you have observed cached or otherwise outdated data or a problem in parts of your code that you have not shown.

How to count the number of user downloads

This code for extract files dir and title. The user download when clicked the file link. I need to count then number of downloads. How to do this with cakephp or php?
downloads_controller.php:
function index() {
$this->set('downloads', $this->paginate());
}
downloads/index.ctp:
<?php
$title = $download['Download']['title'];
// output filetitle
$filename = '/files/'.$download['Download']['filename'];
// output http://localhost/tet/files/un5titled0.rar
echo $this->Html->link($title, $filename,array('escape' => false));
?>
not this way i am afraid.
you either need to redirect from an action (which counts before redirecting) or use Media view to pass it through.
thats how I do it.
In the action you can then raise the count prior to sending the file.
If you want to count downloads, you should create a function that serves those downloads and create a field in your database that increments downloads each time this function is called.. For example
Call the following function from your view passing the $filename and the $id
To try out at first use, taking ID=4 as one of the downloads ID in your DB
http://www.yourdomain.com/downloads/download/4
And Then your controller would be...
Class DownloadsController extends AppController{
// All your other functions here
function download($id = null){
$this->Article->updateAll(
array('Download.count' => 'Download.count+1'),
array('Download.id' => $id)
);
$download = $this->Download->findById($id);
$this->set('filename', $download['Download']['filename']);
//$filename is an array that can then be used in your view to pass the file for download. to find out what is has you can use debug($filename) in your view
}
}
Then you need to create a special layout so the browser knows that the request file is a download and you will also need to create a view for download.ctp. Basically when you click the file link on your page, it will call this function which will use its view to serve the file.
You can access the following which will provide some insight on what needs to be done..
TUTORIAL LINK
There are lots of techniques, though in the simplest way, you can use a text file to do this.
Create a txt file and write 0 (zero) into it.
In your index function, read the content of your file.
$counter = file_read_contents('counter.txt');
Increase the read value by 1.
$counter++;
Write new value into file again.
file_put_contents('counter.txt', $counter);
So, it counts downloads and keep number in that file.
function download($id = null) {
$download = $this->Download->findById($id);
$this->set(compact('download'));
if(!empty($id)) {
// increment the number of items downloads
$this->Download->save(array(
'Download' => array(
'id' => $id,
'counts' => ($download['Download']['counts'] + 1)
)
));
}
header('Location: http://localhost/tet/files/'.$download['Download']['filename']);
exit();
}

drupal adding a user reference field to a template

I have a template file that I want to print a the cck user reference form field on.
Is this possible? Note, this is not the field value, but the field form. Also asking for just the field, not creating a form first and then using drupal_get_form()
Thanks!
Edit: If this is not possible that's fine too, I just would like to know
Edit2: i just need the autocomplete mechanism so I can grab the uid in js from searching for the username
If you just need autocomplete mechanism I would suject you to use jQuery autocomplete plugin - http://docs.jquery.com/Plugins/autocomplete.
you can just output in the template something like that:
print '<input type="text" id="user-autocomplete">';
Then in javascript code
$(document).ready('function(){
$('#user-autocomplete').autocomplete(some-ajax-url-here)
}');
you also will need to create an ajax callback page somewhere in your module:
function YOUR_MODULE_NAME_menu(){
$items = array();
$items['user-autocomplete-ajax-page'] = array(
'title' => 'AJAX:get user',
'page callback' => 'get_user'
);
}
function get_user(){
$sql = 'SELECT uid, name FROM {users} WHERE name LIKE ("%s")';
$result = db_query($sql,$_GET['request']);
$res_str = '';
while($object = db_fetch_object($result)){
$res_str .= $object->name.' ['.$object->uid."]\n";
}
print $res_str;
}
I didn't test the code, but I guess it should work, may be with some minor changes.

Categories